Routing, Form
Lecture 03
Learning Outcomes
After Completing this lesson, you should be able to explain how to
map variable url to a single view function
use static files in Flask application
redirect to different routes
render custom error pages
create, process, and validate form
Routing: Variable Rules
You can add variable sections to a URL by marking sections with
<variable_name>
Your function then receives the <variable_name> as a keyword argument
from markupsafe import escape
@[Link]('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % escape(username)
Routing
Use the route() decorator to bind a view function to a URL
@[Link]('/')
def index():
return render_template('[Link]')
How do you map a variable URL to a single view function?
[Link]
[Link]
...
[Link]
Routing: Variable Rules
You can use a converter to specify the type of the argument like
<converter:variable_name>
@[Link]('/todo/<int:id>')
def show_todo(id):
todos = {0: 'Studying', 1: 'Shopping'}
return todos[id]
Routing: Variable Rules
You can use a converter to specify the type of the argument like
<converter:variable_name>
Converter Types
string
(default) accepts any text without a path
slash like string but also accepts
int slashes
accepts positive integers uuid
float accepts UUID strings
accepts positive floating point values
Routing: Variable Rules
You can use a converter to specify the type of the argument like
<converter:variable_name>
@[Link]('/path/<path:subpath>')
def show_subpath(subpath):
# show the subpath after /path/
return 'Subpath %s' % escape(subpath)
URL Building
To build a URL to a specific function, use the url_for() function
It accepts the name of the view function as its first argument and any
number of keyword arguments, each corresponding to a variable part of the
URL rule
Unknown variable parts are appended to the URL as query parameters
Static Files
To use static files such as css and javascript in your application, create a folder
called static in your package or next to your module
To generate URLs for static files, use the special 'static' endpoint name in
the url_for() function
url_for('static', filename='[Link]')
The file has to be stored on the filesystem as static/[Link]
Integrating Bootstrap CSS framework
Download Bootstrap from [Link]
Extract the javascript and css files and put them inside the
static folder as shown
Integrating Bootstrap CSS framework
Inside your [Link] file you can import the CSS and JS files as shown
below
Errors
If you want to use custom error page, you can use the errorhandler()
decorator
from flask import render_template
@[Link](404)
def page_not_found(error):
return render_template('page_not_found.html'), 404
HTTP Methods
By default, a route only answers to GET requests
You can use the methods argument of the route() decorator to handle
different HTTP methods
from flask import request
@[Link] ('/login', methods=['GET', 'POST'])
def login():
if [Link] == 'POST':
return do_the_login ()
else:
return show_the_login_form ()
Redirects
To redirect a user to another endpoint, use the redirect() function
from flask import abort, redirect, url_for
@[Link]('/')
def index():
return redirect(url_for('login'))
Responses
The return value from a view function is automatically converted into a
response object for you
If you want to get hold of the resulting response object inside the view you
can use the make_response() function
@[Link](404)
def not_found(error):
resp = make_response(render_template('page_not_found.html'), 404)
[Link]['X-Something'] = 'A value'
return resp
Working with Form
WTForms Library
a flexible forms validation and rendering library for Python web
development
it supports features such as data validation, CSRF protection, and
internationalization (I18N)
Working with Form
Flask-WTF Extension
Simple integration of Flask and WTForms, including CSRF, file upload,
and reCAPTCHA, Internationalization
Installation
pip install Flask-WTF
Working with Form
Question
What are common component of an HTML form
Working with Form
The Flask-WTF extension uses Python classes to represent HTML forms
A form class defines the fields of the form as class variables
Example
Let us create a form for accepting todo task information from a user
Sample Code
[Link]
Working with Form
Step - 1: Create a form class (inside [Link] file, for example) by extending
the FlaskForm class and by using field type classes from wtforms package
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
class TaskForm(FlaskForm):
title = StringField('Title')
due_date = StringField('Due Date')
submit = SubmitField('Submit')
Working with Form
Step - 2: Define a route, a view function and pass an instance of the form class
to the template from flask import Flask, render_template
from forms import TaskForm
Required for
CSRF protection app = Flask(__name__)
[Link]['SECRET_KEY']='7ff61fae7049489'
@[Link]('/todo')
def todo():
form = TaskForm()
return render_template('[Link]', form = form)
Working with Form
Step - 3: Define the View using form fields
<form method='POST' style="width: 20em;">
{{ form.csrf_token }}
<div class="form-group">
{{ [Link](class='form-control-label') }}
{{ [Link](class='form-control') }}
</div>
<div class="form-group">
{{ form.due_date.label(class='form-control-label') }}
{{ form.due_date(class='form-control') }}
</div>
{{ [Link](class='btn btn-primary')}}
</form>
Working with Form
Step - 4: Processing Form Data
todos = []
@[Link]('/todo', methods=['GET','POST'])
def todo():
form = TaskForm()
if form.validate_on_submit():
[Link]({'title': [Link],
'due_date': form.due_date.data})
return render_template('[Link]', form = form, todos=todos)
Working with Form
Step - 5: Validation
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from [Link] import DataRequired
class TaskForm(FlaskForm):
title = StringField('Title', validators=[DataRequired()])
due_date = StringField('Due Date')
submit = SubmitField('Submit')
Working with Form
Step - 5: Validation title field
<div class="form-group">
{{ [Link](class='form-control-label') }}
{% if [Link] %}
{{ [Link](class='form-control is-invalid') }}
<div class="invalid-feedback">
{% for error in [Link] %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ [Link](class='form-control') }}
{% endif %}
</div>
References
[Link]
[Link]
[Link]