在FLASK中从html表单中删除method =“delete”

时间:2012-12-17 18:02:42

标签: python flask

我有一个HTML表单:

{% set delete_urls = url_for('store_add') ~ store_id ~ "?__METHOD_OVERRIDE__=DELETE" %}
<form action="{{delete_urls}}" name="delete" method="post" id="{{form_id}}" style="display:none">

并在视图中:

class StoreAdd(MethodView):

    @login_required
    def delete(self,store_id):
        store_selected = request.args['store_id']

        qstr = "DELETE FROM store WHERE store_id=%d AND cust_id=%d"%(store_id,self.cust_id)
        h = pgexec(qstr,False,True)
        h.process()

        flash("deleted the store:%d"%(store_selected))
        return redirect(url_for('store_add'))

store_add = StoreAdd.as_view('store_add')
app.add_url_rule('/storeadd/',
                 defaults={'store_id': 0},
                 view_func=store_add,
                 methods=["GET","PUT"])
app.add_url_rule('/storeadd/',
                 view_func=store_add,
                 methods=["POST"])
app.add_url_rule('/storeadd/<int:store_id>',
                 view_func=store_add,
                 methods=['DELETE','PUT','GET'])

当然实现了路由:

from werkzeug import url_decode
from flask import flash

class MethodRewriteMiddleware(object):

    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        if 'METHOD_OVERRIDE' in environ.get('QUERY_STRING', ''):
            args = url_decode(environ['QUERY_STRING'])
            method = args.get('__METHOD_OVERRIDE__')
            if method in ['GET', 'POST', 'PUT', 'DELETE']:
                method = method.encode('ascii', 'replace')
            environ['REQUEST_METHOD'] = method
        return self.app(environ, start_response)

但是仍然提交删除表单,它无法访问删除方法? 出了什么问题?

编辑:

删除问题如下。 当我提交表单时,它似乎试图“POST”到url:

/storeadd/13?__METHOD_OVERRIDE__=DELETE

但POST网址规则说它只能是:/ storeadd。因此它给出了405 ERROR Page。 因此,应该发生的覆盖永远不会发生。

1 个答案:

答案 0 :(得分:0)

您是否已将此中间件应用于烧瓶应用程序?

app.wsgi_app = MethodRewriteMiddleware(app.wsgi_app)