Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I override the HTTP methods for PUT and DELETE in a Flask Module?

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).

like image 414
Kyle Wild Avatar asked May 26 '11 19:05

Kyle Wild


People also ask

What is HTTP method override?

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.

Which of the following functions can be used to terminate HTTP request with a message and status code Flask?

Flask comes with a handy abort() function that aborts a request with an HTTP error code early.


1 Answers

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.

like image 74
Armin Ronacher Avatar answered Oct 08 '22 05:10

Armin Ronacher