FlaskでhtmlからDELETEやPUTなどのhttpメソッドを扱う方法メモ

はじめに

今勉強用に作ってるWebアプリケーションで、htmlからDELETEメソッドを送りたかったので調べてみると、htmlのformではdeleteやputなどのhttpメソッドが使えないらしい。

対策

↓のページを見つけた

from flask import _request_ctx_stack

@app.before_request
def before_request():
    method = request.form.get('_method', '').upper()
    if method:
        request.environ['REQUEST_METHOD'] = method
        ctx = _request_ctx_stack.top
        ctx.url_adapter.default_method = method
        assert request.method == method

を追加すれば、↓のようにPOSTメソッドname="_method" value="DELETE"を送る。

<form action="{{ url_for('delete_entry', id=10) }}" method="POST">
    <input type="hidden" name="_method" value="DELETE" />
    <input type="submit" value="Delete entry 10" />
</form>

実際にやってみたところ上手くいかず、DELETEメソッドに置き換えれていなかった(POSTのままだった)。とりあえず_methodの値を直接使うことにする。

@app.route('/<username>/<int:task_id>', methods=['POST'])
def complete_task(username,task_id):
    """タスクの達成処理
    """
    if username == session['username']:
        if request.form.get('_method') == 'DELETE':
            # DELETEメソッド
            models.delete_task(username, task_id)
            return redirect(url_for('index'))

        # POSTメソッドの動作
        models.done_task(username, task_id, request.form['done_comment'])
        return redirect(url_for('index'))
    abort(500)

ちゃんと動いたので、このまますすめることにした