- Flask Framework Cookbook(Second Edition)
- Shalabh Aggarwal
- 113字
- 2021-06-24 13:58:10
How to do it...
Flask provides a class named View, which can be inherited to add our custom behavior.
The following is an example of a simple GET request:
from flask.views import View class GetRequest(View): def dispatch_request(self): bar = request.args.get('foo', 'bar') return 'A simple Flask request where foo is %s' % bar app.add_url_rule( '/a-get-request', view_func=GetRequest.as_view('get_request') )
To accommodate both GET and POST requests, we can write the following code:
from flask.views import View class GetPostRequest(View): methods = ['GET', 'POST'] def dispatch_request(self): if request.method == 'GET': bar = request.args.get('foo', 'bar') if request.method == 'POST': bar = request.form.get('foo', 'bar') return 'A simple Flask request where foo is %s' % bar app.add_url_rule( '/a-request', view_func=GetPostRequest.as_view('a_request') )