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.
Templates
Flask comes with the Jinja template engine.
We can use it to render HTML.
It can access the config
, request
, session
, g
,url_for
, and get_flashed_messages
contexts.
config
is the current configuration object.
request
is the current request object.
session
is the current session object.
g
us the request bound object for global variables.
url_for
is the url_for
function.
And get_flashed_messages
is the get_flashes_messages
function.
Standard Filters
We can use filters that are provided by Flask and Jinja.
For example, we can write:
app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def hello_world():
user = {
'first_name': 'james',
'last_name': 'smith'
}
return render_template('index.html', user=user)
templates/index.html
<script type=text/javascript>
const user = {{ user|tojson }};
</script>
to add the user
dictionary.
Then we pass the user
object into the template and use the tojson
filter with it to convert the dictionary to JSON.
So we get:
<script type="text/javascript">
const user = {"first_name": "james", "last_name": "smith"};
</script>
rendered in the template.
Autoescaping
We can disable autoescaping with the autoescape false
block.
For example, we can write:
app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def hello_world():
return render_template(
'index.html',
will_not_be_escaped='<b>will_not_be_escaped</b>'
)
templates/index.html
{% autoescape false %}
<p>{{ will_not_be_escaped }}</p>
{% endautoescape %}
The will_not_be_escaped
isn’t escaped, so the raw HTML string is rendered.
So we’ll see the <b>
tag rendered as bold text.
Registering Filters
We can register our own filters.
For example, we can write:
app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.template_filter('reverse')
def reverse_filter(s):
return s[::-1]
@app.route('/')
def hello_world():
return render_template(
'index.html',
arr=[1, 2, 3]
)
templates/index.html
{% for a in arr | reverse %}
<p>{{a}}</p>
{% endfor %}
We register the reverse
filter with the app.template_filter
decorator.
In the reverse_filter
function, we return the reversed array s
.
Then in the template, we use the reverse
filter and render it.
We can also write:
app.py
from flask import Flask, render_template
app = Flask(__name__)
def reverse_filter(s):
return s[::-1]
app.jinja_env.filters['reverse'] = reverse_filter
@app.route('/')
def hello_world():
return render_template(
'index.html',
arr=[1, 2, 3]
)
to do the same thing.
We put the filter in the app.jinja_env.filters
dictionary.
Context Processors
We can add functions that we can run in templates.
To do that, we use the @app.context_processor
decorator.
For example, we can write:
app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.context_processor
def utility_processor():
def format_price(amount, currency=u'€'):
return u'{0:.2f}{1}'.format(amount, currency)
return dict(format_price=format_price)
@app.route('/')
def hello_world():
return render_template('index.html')
templates/index.html
{{ format_price(1.22) }}
We add th utility_processor
function and applied the @app.context_processor
to it.
Then inside it, we created the format_price
function that returns a formatted currency string.
And then we return a dictionary with the function as the value of the format_price
key.
Now we can call it in index.html
to render a currency string.
Conclusion
We can call functions and use filters in templates with Flask.