Skip to content
Myr

Merge pull request #2277 from jlara310/master

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Improve quickstart's Routing section

authored by David Lord · committed by GitHub · parents 9dd0a0a, 2592f92 · Browse files · 1 file+94 added−150 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+94 added−150 removed

  • other:+94 added−150 removed

1 file+94 added−150 removed

modified:docs/quickstart.rst+94 added-150 removed
157 unmodified lines
158159Routing160-------161162Modern web applications have beautiful URLs. This helps people remember163the URLs, which is especially handy for applications that are used from164mobile devices with slower network connections. If the user can directly165go to the desired page without having to hit the index page it is more166likely they will like the page and come back next time.162Modern web applications use meaningful URLs to help users. Users are more163likely to like a page and come back if the page uses a meaningful URL they can164remember and use to directly visit a page.165168As you have seen above, the :meth:`~flask.Flask.route` decorator is used to169bind a function to a URL. Here are some basic examples::166Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. ::167168 @app.route('/')169 def index():170 return 'Index Page'
1 unmodified line
172 @app.route('/hello')173 def hello():174 return 'Hello, World'175179But there is more to it! You can make certain parts of the URL dynamic and180attach multiple rules to a function.176You can do more! You can make parts of the URL dynamic and attach multiple177rules to a function.178179Variable Rules180``````````````181185To add variable parts to a URL you can mark these special sections as186``<variable_name>``. Such a part is then passed as a keyword argument to your187function. Optionally a converter can be used by specifying a rule with188``<converter:variable_name>``. Here are some nice examples::182You can add variable sections to a URL by marking sections with183``<variable_name>``. Your function then receives the ``<variable_name>``184as a keyword argument. Optionally, you can use a converter to specify the type185of the argument like ``<converter:variable_name>``. ::186187 @app.route('/user/<username>')188 def show_user_profile(username):189 # show the user profile for that user
3 unmodified lines
193 def show_post(post_id):194 # show the post with the given id, the id is an integer195 return 'Post %d' % post_id196200The following converters exist:197 @app.route('/path/<path:subpath>')198 def show_subpath(subpath):199 # show the subpath after /path/200 return 'Subpath %s' % subpath201202=========== ===============================================203`string` accepts any text without a slash (the default)204`int` accepts integers205`float` like ``int`` but for floating point values206`path` like the default but also accepts slashes207`any` matches one of the items provided208`uuid` accepts UUID strings209=========== ===============================================202Converter types:203211.. admonition:: Unique URLs / Redirection Behavior204========== ==========================================205``string`` (default) accepts any text without a slash206``int`` accepts positive integers207``float`` accepts positive floating point values208``path`` like ``string`` but also accepts slashes209``uuid`` accepts UUID strings210========== ==========================================211213 Flask's URL rules are based on Werkzeug's routing module. The idea214 behind that module is to ensure beautiful and unique URLs based on215 precedents laid down by Apache and earlier HTTP servers.212Unique URLs / Redirection Behavior213``````````````````````````````````214217 Take these two rules::215Take these two rules::216219 @app.route('/projects/')220 def projects():221 return 'The project page'217 @app.route('/projects/')218 def projects():219 return 'The project page'220223 @app.route('/about')224 def about():225 return 'The about page'221 @app.route('/about')222 def about():223 return 'The about page'224227 Though they look rather similar, they differ in their use of the trailing228 slash in the URL *definition*. In the first case, the canonical URL for the229 ``projects`` endpoint has a trailing slash. In that sense, it is similar to230 a folder on a filesystem. Accessing it without a trailing slash will cause231 Flask to redirect to the canonical URL with the trailing slash.225Though they look similar, they differ in their use of the trailing slash in226the URL. In the first case, the canonical URL for the ``projects`` endpoint227uses a trailing slash. It's similar to a folder in a file system; if you228access the URL without a trailing slash, Flask redirects you to the229canonical URL with the trailing slash.230233 In the second case, however, the URL is defined without a trailing slash,234 rather like the pathname of a file on UNIX-like systems. Accessing the URL235 with a trailing slash will produce a 404 "Not Found" error.231In the second case, however, the URL definition lacks a trailing slash,232like the pathname of a file on UNIX-like systems. Accessing the URL with a233trailing slash produces a 404 “Not Found” error.234237 This behavior allows relative URLs to continue working even if the trailing238 slash is omitted, consistent with how Apache and other servers work. Also,239 the URLs will stay unique, which helps search engines avoid indexing the240 same page twice.235This behavior allows relative URLs to continue working even if the trailing236slash is omitted, consistent with how Apache and other servers work. Also,237the URLs will stay unique, which helps search engines avoid indexing the238same page twice.239242240.. _url-building:241242URL Building243````````````244248If it can match URLs, can Flask also generate them? Of course it can. To249build a URL to a specific function you can use the :func:`~flask.url_for`250function. It accepts the name of the function as first argument and a number251of keyword arguments, each corresponding to the variable part of the URL rule.252Unknown variable parts are appended to the URL as query parameters. Here are253some examples::245To build a URL to a specific function, use the :func:`~flask.url_for` function.246It accepts the name of the function as its first argument and any number of247keyword arguments, each corresponding to a variable part of the URL rule.248Unknown variable parts are appended to the URL as query parameters.249255 >>> from flask import Flask, url_for256 >>> app = Flask(__name__)257 >>> @app.route('/')258 ... def index(): pass259 ...260 >>> @app.route('/login')261 ... def login(): pass262 ...263 >>> @app.route('/user/<username>')264 ... def profile(username): pass265 ...266 >>> with app.test_request_context():267 ... print(url_for('index'))268 ... print(url_for('login'))269 ... print(url_for('login', next='/'))270 ... print(url_for('profile', username='John Doe'))271 ...272 /273 /login274 /login?next=/275 /user/John%20Doe276277(This also uses the :meth:`~flask.Flask.test_request_context` method, explained278below. It tells Flask to behave as though it is handling a request, even279though we are interacting with it through a Python shell. Have a look at the280explanation below. :ref:`context-locals`).281250Why would you want to build URLs using the URL reversing function251:func:`~flask.url_for` instead of hard-coding them into your templates?284There are three good reasons for this:2522861. Reversing is often more descriptive than hard-coding the URLs. More287 importantly, it allows you to change URLs in one go, without having to288 remember to change URLs all over the place.2892. URL building will handle escaping of special characters and Unicode290 data transparently for you, so you don't have to deal with them.2913. If your application is placed outside the URL root - say, in292 ``/myapplication`` instead of ``/`` - :func:`~flask.url_for` will handle293 that properly for you.2531. Reversing is often more descriptive than hard-coding the URLs.2542. You can change your URLs in one go instead of needing to remember to255 manually change hard-coded URLs.2563. URL building handles escaping of special characters and Unicode data257 transparently.2584. If your application is placed outside the URL root, for example, in259 ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly260 handles that for you.261262For example, here we use the :meth:`~flask.Flask.test_request_context` method263to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context`264tells Flask to behave as though it's handling a request even while we use a265Python shell. See :ref:`context-locals`. ::266296HTTP Methods297````````````267 from flask import Flask, url_for268299HTTP (the protocol web applications are speaking) knows different methods for300accessing URLs. By default, a route only answers to ``GET`` requests, but that301can be changed by providing the ``methods`` argument to the302:meth:`~flask.Flask.route` decorator. Here are some examples::269 app = Flask(__name__)270304 from flask import request271 @app.route('/')272 def index():273 return 'index'274306 @app.route('/login', methods=['GET', 'POST'])275 @app.route('/login')276 def login():308 if request.method == 'POST':309 return do_the_login()310 else:311 return show_the_login_form()277 return 'login'278313If ``GET`` is present, ``HEAD`` will be added automatically for you. You314don't have to deal with that. It will also make sure that ``HEAD`` requests315are handled as the `HTTP RFC`_ (the document describing the HTTP316protocol) demands, so you can completely ignore that part of the HTTP317specification. Likewise, as of Flask 0.6, ``OPTIONS`` is implemented for you318automatically as well.279 @app.route('/user/<username>')280 def profile(username):281 return '{}'s profile'.format(username)282320You have no idea what an HTTP method is? Worry not, here is a quick321introduction to HTTP methods and why they matter:283 with app.test_request_context():284 print(url_for('index'))285 print(url_for('login'))286 print(url_for('login', next='/'))287 print(url_for('profile', username='John Doe'))288323The HTTP method (also often called "the verb") tells the server what the324client wants to *do* with the requested page. The following methods are325very common:289 /290 /login291 /login?next=/292 /user/John%20Doe293327``GET``328 The browser tells the server to just *get* the information stored on329 that page and send it. This is probably the most common method.294HTTP Methods295````````````296331``HEAD``332 The browser tells the server to get the information, but it is only333 interested in the *headers*, not the content of the page. An334 application is supposed to handle that as if a ``GET`` request was335 received but to not deliver the actual content. In Flask you don't336 have to deal with that at all, the underlying Werkzeug library handles337 that for you.297Web applications use different HTTP methods when accessing URLs. You should298familiarize yourself with the HTTP methods as you work with Flask. By default,299a route only answers to ``GET`` requests. You can use the ``methods`` argument300of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods.301::302339``POST``340 The browser tells the server that it wants to *post* some new341 information to that URL and that the server must ensure the data is342 stored and only stored once. This is how HTML forms usually343 transmit data to the server.303 @app.route('/login', methods=['GET', 'POST'])304 def login():305 if request.method == 'POST':306 do_the_login()307 else:308 show_the_login_form()309345``PUT``346 Similar to ``POST`` but the server might trigger the store procedure347 multiple times by overwriting the old values more than once. Now you348 might be asking why this is useful, but there are some good reasons349 to do it this way. Consider that the connection is lost during350 transmission: in this situation a system between the browser and the351 server might receive the request safely a second time without breaking352 things. With ``POST`` that would not be possible because it must only353 be triggered once.310If ``GET`` is present, Flask automatically adds support for the ``HEAD`` method311and handles ``HEAD`` requests according to the the `HTTP RFC`_. Likewise,312``OPTIONS`` is automatically implemented for you.313355``DELETE``356 Remove the information at the given location.357358``OPTIONS``359 Provides a quick way for a client to figure out which methods are360 supported by this URL. Starting with Flask 0.6, this is implemented361 for you automatically.362363Now the interesting part is that in HTML4 and XHTML1, the only methods a364form can submit to the server are ``GET`` and ``POST``. But with JavaScript365and future HTML standards you can use the other methods as well. Furthermore366HTTP has become quite popular lately and browsers are no longer the only367clients that are using HTTP. For instance, many revision control systems368use it.369314.. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt315316Static Files317------------
520 unmodified lines