I am having a hard time trying to modify the Flask request object before routing occurs.
My API Module (not my entire Flask app) depends on faking PUT and DELETE operations by sending a special header. I need to check out the contents of the "-Method" header and modify the Flask Request object accordingly, before Flask does its routing.
This is the short, pythonic, explicit code I'd like to work:
@api.before_request
def method_scrubbing():
if request.headers.has_key('-Method'):
method = request.headers['-Method'].upper()
tagalog.log("in before_request, -Method = {}".format(method), 'force')
if method not in ['PUT', 'DELETE']:
raise ApiMethodException(method)
else:
request.method = method
...but I get a "read only property" error from werkzeug: http://drktd.com/74yk
I've seem Armin's post at http://flask.pocoo.org/snippets/38/ but this appears to be app-wide (not specific to a module).
The X-HTTP-Method-Override HTTP header works somewhat similar to a hack. You can add the header with a value of either PUT or DELETE when invoking your Web API via JavaScript or via an XMLHttpRequest object from a web browser using an HTTP POST call.
Flask comes with a handy abort() function that aborts a request with an HTTP error code early.
Werkzeug has the assumption that the request is only modified in a WSGI middleware or before Werkzeug has access to the data. The reason is that this way Werkzeug does not have to monitor the WSGI environment to see if it would have to invalidate caches or change behavior.
In this particular case you might be successful however if you are carefully by modifying the underlying WSGI environment:
request.environ['REQUEST_METHOD'] = 'something'
After that request.method
should show "something" and the behavior should change to form parsing. I have not tried this and don't know if it will work. Personally I would write a middleware that does the rewriting for the whole application or does some simple url prefix matching for that behavior probably.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With