Introduction To Flask
Introduction To Flask
Creating a Route
Routes in a Flask app can be created by defining a view function and
associating a URL with it using the route() decorator. Routes specify how
the Flask app handles requests it receives, such as what to display on the
webpage at a certain URL.
@app.route('/')
def hello_world():
return 'Hello, World!'
# Output: The text `Hello, World!` is displayed at the URL path '/'
# Output: The text `Hello, World!` is displayed as a level 1 heading at the URL path '/'
Variable Rules
Variable rules allow a Flask app to respond to dynamic URLs. Variable
sections of a URL can be indicated by angular brackets and an optional
converter: <converter:variable_name>. These variable parts will then be passed to
the view function as arguments.
# Responds to `/page/1`, `/page/20`, etc.
@app.route('/page/<int:pg_num>')
def content(pg_num):
return f'<h1>Displaying results for page {pg_num}</h1>'
Jinja2 Templates and Forms
Flask Templates
Flask uses templates to expand the functionality of a web application
while maintaining a simple and organized file structure. Templates are
enabled using the Jinja2 template engine and allow data to be shared
and processed before being turned in to content and sent back to the
client.
render_template Function
The render_template() function renders HTML files for display in the web
browser using the Jinja2 template engine. Its sole positional argument is
the name of the template to be rendered. Keyword arguments can be
added to support application variables within the template.
## The template variables are substituted into "my_template.html" using the following format
## {{ template_var1 }} and {{ template_var2 }}
Template Variable Filters
Filters are applied to template variables and perform a small focused
action. Filters follow a variable and are separated by the pipe, |, character.
This syntax works inside expression {{ }} and statement {% %}delimiters.
Template if Statements
{% if condition %} statements are used in templates to control the content
that is returned from Flask routes. Content associated with
an if statement is enclosed in blocks starting with {% if condition %} and
closing with {% endif %}. else and elif can be used with if statements to
further control the content.
Template for Loops
For loops are used in templates to repeat content or iterate through data
during Jinja2 template engine processing. For loops are contained inside
statement delimiters with the following syntax {% for local_var in iterator
%}. Content inside the block is repeated where the block start with
the for statement and is closed by {% endfor %}.
Template Inheritance
Jinja templates use inheritance to share content from one template
across multiple templates.
{% block content %}
<p>Because of inheritance this file has html and body tags.</p>
{% endblock %}
url_for Function
The function url_for() is used within a template to navigate a site through
the route function names and not the possibly volatile URL strings.
Calling url_for() with the route function name as it’s parameter is safer way
to indicate routes within templates since URL strings can change based
on a sites changing file structure.
FlaskForm Class
Inheriting from the FlaskForm class gives an app defined class the
functionality such as template representation, gathering data and
providing validation. Used in conjunction with WTForm Fields, FlaskForm
functionality gives an easy path over how forms are displayed and how
valid data is collected within an application. FlaskForm is imported through
the flask_wtf module.
app = Flask(__name__)
app.config["SECRET_KEY"] = "secret_string"
class MyForm(FlaskForm):
## Form elements initialized here
WTForm Fields
WTForm field objects are a simple way to implement web form fields
such as text fields and submit buttons. Imported from the wtforms module
and initialized inside a FlaskForm subclass, field objects provide the
representation and functionality of web form elements. Some common
tasks of field objects are label management, field validation and data
handling.
StringField()
SubmitField()
TextAreaField()
BooleanField()
RadioField()
class MyForm(FlaskForm):
myStringField("My Text")
mySubmitField("Submit My Form")
Form Validation
Web form validation is the process of ensuring the correct data is
collected by the form before it is sent to the server for processing.
In a web form, validators are used to identify the fields that require
specifc data or formats upon submitting the form. This can be as simple
as requiring data to be present, to more specific formats such as dates,
phone numbers and email addresses. Form field validators can be added
to the field’s instantiation and are imported from
the wtforms.validators module. Check the WTForms Validators
documentation for more information.
app = Flask(__name__)
class MyForm(FlaskForm):
my_field = StringField("Email", validators=[DataRequired(), Email()])
redirect() Function
The redirect() function is used within a Flask application to move from one
route to another. Used in a routes return statement, redirect() takes a URL
string as an argument to identify the correct route to jump to. In many
cases redirect() is used with url_for() as its argument to avoid using URL
strings.
Previous