How to correctly redirect to a route with a specific method?


#1

I would like to redirect to a route that allows multiple methods.

When using the following, redirect happens as a GET request. However the route message accepts POST request also other than the default GET request.

contactform_schema = {
    'fullname': {'type': 'string', 'maxlength': 80, 'required': True},
    'email': {
        'type': 'string', 
        'regex': emailregx, 
        'required': True
        },
    'phone': {'type': 'string', 'maxlength': 18, 'required': True},
    'message': {'type': 'string', 'maxlength': 1200, 'required': True},
    'vehicle_count': {'type': 'number', 'min':0, 'max':1000000, 'required': True}
    }
@app.route("/contactform", methods=['POST','OPTIONS'])
@validate_json(contactform_schema)
def pocontactformst(request):
    phone = request.json.get('phone', None)
    if phone_check(phone) == True :
        return response.redirect('/message',content_type='application/json')
    else:
        return json({'status': 'PhoneNumberFormat.E164:false'}, 403)

Might be a trivial question given I just started recently with Sanic :slight_smile:

As a background I was trying to use the sanic_crud from the listed Sanic extensions. In the above code I am just adding an extra layer of validation before redirecting the POST request to the route message created by sanic_crud library. On that message route one can create a messages in the database via a POST request with a JSON payload.

app = Sanic(__name__)
generate_crud(app, [ message])
app.run(host="0.0.0.0", port=8000, debug=True)

#2

@platomaniac, first of all, welcome to the Sanic Community Forums! :smile:

Your question seems quite interesting, to be honest. You perform a POST and want it to be redirected (making the browser / http(s) client resubmit again the payload). I don’t know if this is the best approach to do that (since you’ll be receiving the payload twice), but if that’s okay with you, let’s keep on.

Sanic’s default HTTP status code for redirecting is 302, which only exists for compatibility purposes nowadays since it was superseeded by 303 and 307 with the HTTP/1.1 specs. What happens with 302 in clients that already understands HTTP/1.1 specs is to perform a 303 operation (most likely, I don’t know the inner works of all of them), which in this case redirects strictly to a GET. Always. So that’s what might be happening to your application.

Now, if you are sure that your clients and server will always handle HTTP/1.1, then you can try to add status=307 to your redirect method parameters, because 307 should redirect GET and POST - but there’s no guarantee on that (I know, that’s a little obscure, that’s why I said it was an interesting question in the beggining).

You can read more information here. Let me know if that works out for you or if you need some further advice :wink: