October 2018
Intermediate to advanced
332 pages
8h 9m
English
Often, when functions handle multiple HTTP methods, the code can become difficult to read due to large sections of code nested within if statements, as demonstrated in the following:
@app.route('/user', methods=['GET', 'POST', 'PUT', 'DELETE'])
def users():
if request.method == 'GET':
...
elif request.method == 'POST':
...
elif request.method == 'PUT':
...
elif request.method == 'DELETE':
...
This can be solved with the MethodView class. MethodView allows each method to be handled by a different class method to separate concerns:
from flask.views import MethodView class UserView(MethodView): def get(self): ... def post(self): ... def put(self): ... def delete(self): ... app.add_url_rule( '/user', view_func=UserView.as_view('user') ...