Build Python Web Apps with Flask Flashcards
Introduction to Flask
Creating Flask App Object
The Python flask module contains all the classes and functions needed for building a Flask app. The Flask class can be imported to create the main application object. It takes the name of the app as an argument.
# Import Flask class from flask import Flask Create Flask object app = Flask(\_\_name\_\_)
Introduction to Flask
Running Flask App
A Flask app can be run by exporting the FLASK_APP environment variable and running flask run in the terminal.
$ export FLASK_APP=app.py $ flask run
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 '/'
Introduction to Flask
Returning HTML From Route
In a Flask app, HTML can be returned from a view function to be rendered on a webpage. The HTML can be returned as a string.
@app.route('/') def hello_world(): return '<h1>Hello, World!</h1>' Output: The text `Hello, World!` is displayed as a level 1 heading at the URL path '/'
Introduction to Flask
Variable Rules
Responds to /page/1
, /page/20
, etc.
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.</converter:variable_name>
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.
where render_template processes template files in the “templates” directory. The “templates” directory located inside the running application directory.
├── app_dir │ ├── templates │ │ ├── my_template.html │ ├── app.py
Jinja2 Templates and Forms
Template Variables
Template variables are representations of application data that are used inside templates. Created using keyword arguments in render_template, template variables are substituted into a template when using expression delimiters {{ }}
Used in Jinja templates, expression delimiters {{ }} surround expressions such as variables to be identified by the template engine.
Jinja2 Templates and Forms
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.
More information on filters can be found in the Jinja documentation.
Jinja2 Templates and Forms
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.
Statement delimiters {% %} surround control statements such as if and for to be identified by the Jinja 2 template engine.
Jinja2 Templates and Forms
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 %}.
Statement delimiters {% %} surround control statements such as if and for to be identified by the Jinja 2 template engine.
Jinja2 Templates and Forms
Template Inheritance
Jinja templates use inheritance to share content from one template across multiple templates.
The block statement is used to identify the location in each file to establish inheritance. In the parent file {% block identifier %} and {% endblock %} are used to identify what line to substitute inherited content. In the child file {% block identifier %} and {% endblock %} surround the content to be substituted.
The extends statement identifies the parent file another template will share content with. Inserted at the top of the child file, {% extends filename %} identifies which parent file to insert the block content into.
Jinja2 Templates and Forms
Flask Web Forms
Flask provides a simple workflow to implement web forms and gather data while ensuring proper form validation. Using the modules WTForms and Flask-WTF, forms can be created using a class structure to create form elements and collect their data through inherited functionality. Requests can be analyzed using Flasks request object.
Jinja2 Templates and Forms
request Object
When it comes to HTML web forms, the Flask request object provides a way to collect data through the client POST request. The data from a form field can be accessed using the field name as a key to the request objects form attribute.
A Flask route must add “POST” to its methods keyword argument. By default methods is set to [“GET”].
## accessing data from "first_name" field @app.route('/', methods=["GET", "POST"]) def index(): if len(request.form) > 0: name_data = request.form["first_name"]
Jinja2 Templates and Forms
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.
The url_for() function needs to be called within expression delimiters {{ }} in order to be processed by the Jinja2 template engine. Keyword arguments can be added to the function call to pass variables to the Flask app route.
<a href="{{ url_for('index') }}">Link To Index</a> <a href="{{ url_for('another_route', route_var=some_template_var) }}">Another Route With Variable</a>
Jinja2 Templates and Forms
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.
The “SECRET_KEY” variable in the Flask application’s configuration must be set in order to enable CSRF protection. This is necessary to create forms using FlaskForm.
from flask import Flask from flask_wtf import FlaskForm app = Flask(\_\_name\_\_) app.config["SECRET_KEY"] = "secret_string" class MyForm(FlaskForm): ## Form elements initialized here