Search code examples
pythonflaskhidden-field

How to handle a put request from the browser in Flask?


Coming from an express.js background, I'm quite used to the method-override middleware which enables you to handle non browser supported HTTP verbs (e.g PUT, DELETE, etc) via a hidden input tag.

ex)

    <input type="hidden" name="_method" value="PUT">

How do I mimic this middleware in Flask? Flask does not automatically handle these hidden inputs, so I am unable to process requests other than GET or POST. An excerpt of my code can be found below.

@blueprint.route('/news/<int:article_id>', methods=['GET','PUT','DELETE'])
def article(article_id):
if is_logged_in() and is_admin():
        if request.method == 'PUT':
            #do something

<form action="/news/{{ post.id }}" method="post">
    {{ form.hidden_tag() }}
    <input type="hidden" name="_method" value="PUT">
    {{ form.title.label }} {{ form.title }}
    {{ form.body.label }} {{ form.body }}
    {{ form.submit }}
</form>

Edit: Found a solution: http://flask.pocoo.org/snippets/38/


Solution

  • This doesn't really have anything to do with Flask (other than your templating engine came with it, I suppose) - you still have to generate an HTML page that will tell the browser to use PUT.

    The HTML form element cannot be used for anything other than POST or GET directly, so any support for other methods should be done via XMLHttpRequest in javascript.

    It is also possible to "tunnel" other request methods through POST by having a hidden field (as you have shown above) and having the server do the conversion for you, but it's not particularly efficient. You can see an example of this in a previous SO question, although I would not recommend this over XMLHttpRequest as it requires server support you probably shouldn't rely on.