Context Processors in Flask API

Introduction

I will explain here about the context processors in Python based web Flask API. Flask is a light-weight framework with a set of rich features for creating wonderful web application in Python programming language. In standard context of the flask API, there are some global variables which are, by default, available in Jinja 2 templates and you can easily use these variables throughout your web application’s template files.

Such global variables are flask.config, flask.request, flask.session, flask.g.

There are some global functions as well, such as flask.url_for(), flask.get_flashed_messages().

Context Processor – Variable

Now what if you need to inject a new variable in the context of templates?

Therefore to inject a new variable into the context of templates, flask provides a concept called context processor.

Context processors run before the template gets rendered and has the ability to inject new values into the context of template.

A context processor is a function that returns a dictionary, which is actually a pair of key and value pair and this key and value pair merged with the template context.

From the documentation consider the following example,

@app.context_processor
def inject_user():
    return dict(user=g.user)

In the above example notice a decorator @app.context_processor has been used to inject a new variable into the context of template.

The variable user is available in the template context in your app.

Here g is the global variable provided by the flask API. You can provide your own value to the above variable user.

To use the variable user in your template simply write {{user}} in your template file wherever you need to inject.

For example, let’s say you want to display current year in the footer of your web page along with copyright text. It’s not a good idea to edit the template file on every new year and change the year’s value. So I will create a function and decorate with @app.context_processor to make the variable available in the template context.

Simply write the below function:

@app.context_processor
def inject_now():
    return {'now': datetime.utcnow()}

The context processor above makes the now variable available to all templates and you can inject into templates as follows:

{{now}}

The above variable will print the date time value in UTC time zone in the below format:

2020-09-19 09:08:20.727182

To print the year value using the above variable you need to access the attribute year of the variable now. For example,

{{now.year}}

The above snippet will print value 2020.

Context Processor – Function

A context processor can also make functions available in the template context.

Let’s say you want to format the amount with two decimal value, then you generally want to create a function similar to the below:

@app.context_processor
def utility_processor():
    def format_price(amount, currency='₹'):
        return '{1}{0:.2f}'.format(amount, currency)
    return dict(format_price=format_price)

The context processor above makes the format_price() function available to all templates.

You can call the above context processor function in the template file as shown below:

{{ format_price(100) }}
{{ format_price(100.33) }}

The above code snippets will give you output as follows:

₹100.00
₹100.33

Hope you got an idea how context processors work in Python based flask web framework.

Thanks for reading.

Leave a Reply

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