@ -159,9 +159,11 @@ Have another debugger in mind? See :ref:`working-with-debuggers`.
Routing
Routing
-------
-------
Modern web applications use meaningful URLs to help users. Users are more likely to like a page and come back if the page uses a meaningful URL they can remember and use to directly visit a page.
Modern web applications use meaningful URLs to help users. Users are more
likely to like a page and come back if the page uses a meaningful URL they can
remember and use to directly visit a page.
As you saw in the minimal application, you can use the :meth:`~flask.Flask.route` decorator to bind a function to a meaningful URL. For example::
Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. ::
@app.route('/')
@app.route('/')
def index():
def index():
@ -171,12 +173,16 @@ As you saw in the minimal application, you can use the :meth:`~flask.Flask.route
def hello():
def hello():
return 'Hello, World'
return 'Hello, World'
You can do more! You can make parts of the URL dynamic and attach multiple rules to a function.
You can do more! You can make parts of the URL dynamic and attach multiple
rules to a function.
Variable Rules
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. Optionally, you can use a converter to specify a rule with ``<converter:variable_name>``. For example::
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. Optionally, you can use a converter to specify the type
of the argument like ``<converter:variable_name>``. ::
@app.route('/user/<username>')
@app.route('/user/<username>')
def show_user_profile(username):
def show_user_profile(username):
@ -195,75 +201,91 @@ You can add variable sections to a URL by marking sections with ``<variable_name
Flask's URL rules are based on Werkzeug's routing module. The routing module creates meaningful and unique URLs based on precedents laid down by Apache and earlier HTTP servers.
Take these two rules::
Take these two rules::
@app.route('/projects/')
def projects():
return 'The project page'
@app.route('/projects/')
@app.route('/about')
def projects():
def about():
return 'The project page'
return 'The about page'
@app.route('/about')
Though they look similar, they differ in their use of the trailing slash in
def about():
the URL. In the first case, the canonical URL for the ``projects`` endpoint
return 'The about page'
uses a trailing slash. It's similar to a folder in a file system; if you
access the URL without a trailing slash, Flask redirects you to the
canonical URL with the trailing slash.
Though they look similar, they differ in their use of the trailing slash in the URL *definition*. In the first case, the canonical URL for the ``projects`` endpoint uses a trailing slash. It's similar to a folder in a file system, and if you access the URL without a trailing slash, Flask redirects you to the canonical URL with the trailing slash.
In the second case, however, the URL definition lacks a trailing slash,
like the pathname of a file on UNIX-like systems. Accessing the URL with a
In the second case, however, the URL definition lacks a trailing slash like the pathname of a file on UNIX-like systems. Accessing the URL with a trailing slash produces a 404 “Not Found” error.
trailing slash produces a 404 “Not Found” error.
This behavior allows relative URLs to continue working even if the trailing
slash is omitted, consistent with how Apache and other servers work. Also,
the URLs will stay unique, which helps search engines avoid indexing the
same page twice.
This behavior allows relative URLs to continue working even if the trailing
slash is omitted, consistent with how Apache and other servers work. Also,
the URLs will stay unique, which helps search engines avoid indexing the
same page twice.
.._url-building:
.._url-building:
URL Building
URL Building
````````````
````````````
Flask can match URLs, but can it also generate them? Yes! To build a URL to a specific function, you can use the :func:`~flask.url_for` function. It accepts the name of the 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.
To build a URL to a specific function, use the :func:`~flask.url_for` function.
It accepts the name of the 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.
Why would you want to build URLs using the URL reversing function
Why would you want to build URLs using the URL reversing function
:func:`~flask.url_for` instead of hard-coding them into your templates? Three good reasons:
:func:`~flask.url_for` instead of hard-coding them into your templates?
1. Reversing is often more descriptive than hard-coding the URLs. More importantly, you can change your URLs in one go instead of needing to remember to manually change hard-coded URLs.
1. Reversing is often more descriptive than hard-coding the URLs.
2. URL building handles escaping of special characters and Unicode data transparently.
2. You can change your URLs in one go instead of needing to remember to
3. If your application is placed outside the URL root, for example, in ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly handles that for you.
manually change hard-coded URLs.
3. URL building handles escaping of special characters and Unicode data
transparently.
For example, here we use the :meth:`~flask.Flask.test_request_context` method to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context` tells Flask to behave as though it's handling a request even while we use a Python shell. Also see, :ref:`context-locals`.
4. If your application is placed outside the URL root, for example, in
``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly
Example::
handles that for you.
>>> from flask import Flask, url_for
For example, here we use the :meth:`~flask.Flask.test_request_context` method
>>> app = Flask(__name__)
to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context`
>>> @app.route('/')
tells Flask to behave as though it's handling a request even while we use a
Web application communicate using HTTP and use different methods for accessing URLs. You should familiarize yourself with the HTTP methods as you work with Flask. By default, a route only answers to ``GET`` requests. You can use the ``methods`` argument of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods. For example::
Web applications use different HTTP methods when accessing URLs. You should
familiarize yourself with the HTTP methods as you work with Flask. By default,
a route only answers to ``GET`` requests. You can use the ``methods`` argument
of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods.
::
@app.route('/login', methods=['GET', 'POST'])
@app.route('/login', methods=['GET', 'POST'])
def login():
def login():
@ -281,7 +307,9 @@ Web application communicate using HTTP and use different methods for accessing U
else:
else:
show_the_login_form()
show_the_login_form()
If ``GET`` is present, Flask automatically adds support for the ``HEAD`` method and handles ``HEAD`` requests according to the the `HTTP RFC`_. Likewise, as of Flask 0.6, ``OPTIONS`` is automatically implemented for you.
If ``GET`` is present, Flask automatically adds support for the ``HEAD`` method
and handles ``HEAD`` requests according to the the `HTTP RFC`_. Likewise,