Changing request method using hidden field _method in Flask

前端 未结 2 820
清酒与你
清酒与你 2020-12-17 21:40

Started picking up Python and Flask as a learning exercise, and coming from PHP/Symfony2, I could add a hidden _method field to a form to override the POST method with eithe

2条回答
  •  被撕碎了的回忆
    2020-12-17 22:43

    You could use the MethodView from flask.views and dispatch it to the right methods. I have created a simple Flask App to demonstrate it.

    from flask import Flask, jsonify, request
    from flask.views import MethodView
    
    app = Flask(__name__)
    
    class MyView(MethodView):
    
        def get(self):
            return jsonify({'method': 'GET'})
    
        def post(self):
            method = request.form.get('_method', 'POST')
            if method == 'POST':
                return jsonify({'method':method})
            else:
                if hasattr(self, method.lower()):            
                    return getattr(self, method.lower())()
                else:
                    return jsonify({'method': 'UNKNOWN'})
    
        def put(self):
            return jsonify({'method': 'PUT'})
    
        def delete(self):
            return jsonify({'method': 'DELETE'})
    
        def create(self):
            # NOT A HTTP VERB
            return jsonify({'method': 'CREATE'})
    
    app.add_url_rule('/', view_func=MyView.as_view('myview'))
    
    if __name__ == "__main__":
        app.run(debug=True)
    

提交回复
热议问题