Categories
Flask

Python Web Development with Flask — Pluggable Views

Spread the love

Flask is a simple web framework written in Python.

In this article, we’ll look at how to develop simple Python web apps with Flask.

Pluggable Views

Flask has pluggable views.

They use classes to render views instead of functions.

For example, we can write:

app.py

from flask import Flask, render_template
from flask.views import View

app = Flask(__name__)

class ShowUsers(View):

    def dispatch_request(self):
        users = [
            {
                'name': 'james'
            },
            {
                'name': 'mary'
            },
        ]
        return render_template('users.html', users=users)

app.add_url_rule('/users/', view_func=ShowUsers.as_view('show_users'))

templates/users.html

{% for u in users %}
<p>{{u.name}}</p>
{% endfor %}

We add the ShowUsers class which inherited from the View class.

It has the dispatch_request method that renders the template with some data.

Then to map the class to a URL, we call the app.add_url_rule method with the URL path and the view_func parameter.

The ShowUsers.as_view method takes the name of the view that we’ll have.

We can make this code more flexible by providing a base class for rendering the template.

Then we create a subclass with the data to render the view.

To do that, we can write:

app.py

from flask import Flask, render_template
from flask.views import View

app = Flask(__name__)

class ListView(View):
    def get_template_name(self):
        raise NotImplementedError()

    def render_template(self, context):
        return render_template(self.get_template_name(), **context)

    def dispatch_request(self):
        context = {'objects': self.get_objects()}
        return self.render_template(context)

class UserView(ListView):
    def get_template_name(self):
        return 'users.html'

    def get_objects(self):
        return [
            {
                'name': 'james'
            },
            {
                'name': 'mary'
            },
        ]

app.add_url_rule('/users/', view_func=UserView.as_view('show_users'))

templates/users.html

{% for u in objects %}
<p>{{u.name}}</p>
{% endfor %}

The ListView component is the base class for the view.

get_template_name is implement in the subclasses of this class.

render_template calls render_template from Flask. with the template name returned from the get_template_name method.

The rest of the arguments are passed in from the context object.

dispatch_request passes in the context into the render_template method.

The UserView class extends the ListView class and returns the template name in the get_template_name method.

And get_objects has the objects array that we render in the template.

Method Hints

We can set the methods that are allowed.

For example, we can write:

from flask import Flask, request
from flask.views import View

app = Flask(__name__)

class MyView(View):
    methods = ['GET', 'POST']

    def dispatch_request(self):
        if request.method == 'POST':
            return 'post'
        return 'get'

app.add_url_rule('/myview', view_func=MyView.as_view('myview'))

to add the MyView class.

It has the methods array that sets the request types that are allowed.

In the dispatch_request method, we check the request method with the request.method property and return the response accordingly.

Then we map the class to a URL with the app;.add_url_rule method.

Method Based Dispatching

We can dispatch methods with methods.

For example, we can write:

from flask import Flask, request
from flask.views import MethodView

app = Flask(__name__)

class UserAPI(MethodView):
    def get(self):
        return 'get'

    def post(self):
        return 'post'

app.add_url_rule('/users/', view_func=UserAPI.as_view('users'))

We have the UserAPI class which extends the MethodView class.

Then we add the get method to accept GET requests and the post method to accept POST requests.

And then we call app.add_url_rule to map that class to a URL.

Now when we make a GET request, we see 'get' and when we make a POST request, we see 'post' .

Conclusion

Pluggable views is a useful way for organizing views with Flask.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *