Book Image

Flask Framework Cookbook

By : Shalabh Aggarwal
Book Image

Flask Framework Cookbook

By: Shalabh Aggarwal

Overview of this book

Table of Contents (19 chapters)
Flask Framework Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Class-based views


Flask introduced the concept of pluggable views in version 0.7; this added a lot of flexibility to the existing implementation. We can write views in the form of classes; these views can be written in a generic fashion and allow for an easy and understandable inheritance.

Getting ready

Refer to the previous recipe, Writing function-based views and URL routes, to understand the basic function-based views first.

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 the GET and POST requests, we can write the following code:

from flask.views import View

class GetPostRequest(View):
    methods...