Skip to Content
Mastering Flask
book

Mastering Flask

by Jack Stouffer
September 2015
Intermediate to advanced
288 pages
5h 30m
English
Packt Publishing
Content preview from Mastering Flask

Class-based views

In most Flask apps, views are handled by functions. However, when many views share common functionality or there are pieces of code that could be broken out into separate functions, it would be useful to implement our views as classes to take advantage of inheritance.

For example, if we have views that render a template, we could create a generic view class that keeps our code DRY:

from flask.views import View

class GenericView(View):
    def __init__(self, template):
        self.template = template
        super(GenericView, self).__init__()

    def dispatch_request(self):
        return render_template(self.template)

app.add_url_rule(
    '/', view_func=GenericView.as_view(
        'home', template='home.html'
    )
)

The first thing to note about this code is the dispatch_request() ...

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

An Introduction to Flask

An Introduction to Flask

Miguel Grinberg
Flask Blueprints

Flask Blueprints

Joel Perras
Flask By Example

Flask By Example

Gareth Dwyer

Publisher Resources

ISBN: 9781784393656Supplemental Content