Skip to Content
Mastering Flask Web Development - Second Edition
book

Mastering Flask Web Development - Second Edition

by Daniel Gaspar, Jack Stouffer
October 2018
Intermediate to advanced
332 pages
8h 9m
English
Packt Publishing
Content preview from Mastering Flask Web Development - Second Edition

Method class views

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') ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Flask Web Development, 2nd Edition

Flask Web Development, 2nd Edition

Miguel Grinberg
Flask Web Development

Flask Web Development

Miguel Grinberg

Publisher Resources

ISBN: 9781788995405Supplemental Content