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
Provenance
- Commit
c01ddc5- Tree
ce3cdbd- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
9dd0a0a- Parent 2
2592f92
1 file changed+94 added−150 removed
modified:docs/quickstart.rst+94 added-150 removed
157 unmodified lines158 159 Routing160 -------161 162-Modern web applications have beautiful URLs. This helps people remember163-the URLs, which is especially handy for applications that are used from164-mobile devices with slower network connections. If the user can directly165-go to the desired page without having to hit the index page it is more166-likely they will like the page and come back next time.162+Modern web applications use meaningful URLs to help users. Users are more163+likely to like a page and come back if the page uses a meaningful URL they can164+remember and use to directly visit a page.165 168-As you have seen above, the :meth:`~flask.Flask.route` decorator is used to169-bind a function to a URL. Here are some basic examples::166+Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. ::167 168 @app.route('/')169 def index():170 return 'Index Page'1 unmodified line172 @app.route('/hello')173 def hello():174 return 'Hello, World'175 179-But there is more to it! You can make certain parts of the URL dynamic and180-attach multiple rules to a function.176+You can do more! You can make parts of the URL dynamic and attach multiple177+rules to a function.178 179 Variable Rules180 ``````````````181 185-To 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 your187-function. Optionally a converter can be used by specifying a rule with188-``<converter:variable_name>``. Here are some nice examples::182+You can add variable sections to a URL by marking sections with183+``<variable_name>``. Your function then receives the ``<variable_name>``184+as a keyword argument. Optionally, you can use a converter to specify the type185+of the argument like ``<converter:variable_name>``. ::186 187 @app.route('/user/<username>')188 def show_user_profile(username):189 # show the user profile for that user3 unmodified lines193 def show_post(post_id):194 # show the post with the given id, the id is an integer195 return 'Post %d' % post_id196 200-The following converters exist:197+ @app.route('/path/<path:subpath>')198+ def show_subpath(subpath):199+ # show the subpath after /path/200+ return 'Subpath %s' % subpath201 202-=========== ===============================================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-=========== ===============================================202+Converter types:203 211-.. 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+========== ==========================================211 213- 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.212+Unique URLs / Redirection Behavior213+``````````````````````````````````214 217- Take these two rules::215+Take these two rules::216 219- @app.route('/projects/')220- def projects():221- return 'The project page'217+ @app.route('/projects/')218+ def projects():219+ return 'The project page'220 223- @app.route('/about')224- def about():225- return 'The about page'221+ @app.route('/about')222+ def about():223+ return 'The about page'224 227- 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.225+Though they look similar, they differ in their use of the trailing slash in226+the URL. In the first case, the canonical URL for the ``projects`` endpoint227+uses a trailing slash. It's similar to a folder in a file system; if you228+access the URL without a trailing slash, Flask redirects you to the229+canonical URL with the trailing slash.230 233- 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.231+In the second case, however, the URL definition lacks a trailing slash,232+like the pathname of a file on UNIX-like systems. Accessing the URL with a233+trailing slash produces a 404 “Not Found” error.234 237- 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.235+This behavior allows relative URLs to continue working even if the trailing236+slash is omitted, consistent with how Apache and other servers work. Also,237+the URLs will stay unique, which helps search engines avoid indexing the238+same page twice.239 242-240 .. _url-building:241 242 URL Building243 ````````````244 248-If it can match URLs, can Flask also generate them? Of course it can. To249-build a URL to a specific function you can use the :func:`~flask.url_for`250-function. It accepts the name of the function as first argument and a number251-of keyword arguments, each corresponding to the variable part of the URL rule.252-Unknown variable parts are appended to the URL as query parameters. Here are253-some examples::245+To build a URL to a specific function, use the :func:`~flask.url_for` function.246+It accepts the name of the function as its first argument and any number of247+keyword arguments, each corresponding to a variable part of the URL rule.248+Unknown variable parts are appended to the URL as query parameters.249 255- >>> 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%20Doe276-277-(This also uses the :meth:`~flask.Flask.test_request_context` method, explained278-below. It tells Flask to behave as though it is handling a request, even279-though we are interacting with it through a Python shell. Have a look at the280-explanation below. :ref:`context-locals`).281-250 Why would you want to build URLs using the URL reversing function251 :func:`~flask.url_for` instead of hard-coding them into your templates?284-There are three good reasons for this:252 286-1. 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.289-2. URL building will handle escaping of special characters and Unicode290- data transparently for you, so you don't have to deal with them.291-3. If your application is placed outside the URL root - say, in292- ``/myapplication`` instead of ``/`` - :func:`~flask.url_for` will handle293- that properly for you.253+1. Reversing is often more descriptive than hard-coding the URLs.254+2. You can change your URLs in one go instead of needing to remember to255+ manually change hard-coded URLs.256+3. URL building handles escaping of special characters and Unicode data257+ transparently.258+4. If your application is placed outside the URL root, for example, in259+ ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly260+ handles that for you.261 262+For example, here we use the :meth:`~flask.Flask.test_request_context` method263+to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context`264+tells Flask to behave as though it's handling a request even while we use a265+Python shell. See :ref:`context-locals`. ::266 296-HTTP Methods297-````````````267+ from flask import Flask, url_for268 299-HTTP (the protocol web applications are speaking) knows different methods for300-accessing URLs. By default, a route only answers to ``GET`` requests, but that301-can be changed by providing the ``methods`` argument to the302-:meth:`~flask.Flask.route` decorator. Here are some examples::269+ app = Flask(__name__)270 304- from flask import request271+ @app.route('/')272+ def index():273+ return 'index'274 306- @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'278 313-If ``GET`` is present, ``HEAD`` will be added automatically for you. You314-don't have to deal with that. It will also make sure that ``HEAD`` requests315-are handled as the `HTTP RFC`_ (the document describing the HTTP316-protocol) demands, so you can completely ignore that part of the HTTP317-specification. Likewise, as of Flask 0.6, ``OPTIONS`` is implemented for you318-automatically as well.279+ @app.route('/user/<username>')280+ def profile(username):281+ return '{}'s profile'.format(username)282 320-You have no idea what an HTTP method is? Worry not, here is a quick321-introduction 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'))288 323-The HTTP method (also often called "the verb") tells the server what the324-client wants to *do* with the requested page. The following methods are325-very common:289+ /290+ /login291+ /login?next=/292+ /user/John%20Doe293 327-``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.294+HTTP Methods295+````````````296 331-``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.297+Web applications use different HTTP methods when accessing URLs. You should298+familiarize yourself with the HTTP methods as you work with Flask. By default,299+a route only answers to ``GET`` requests. You can use the ``methods`` argument300+of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods.301+::302 339-``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()309 345-``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.310+If ``GET`` is present, Flask automatically adds support for the ``HEAD`` method311+and handles ``HEAD`` requests according to the the `HTTP RFC`_. Likewise,312+``OPTIONS`` is automatically implemented for you.313 355-``DELETE``356- Remove the information at the given location.357-358-``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.362-363-Now the interesting part is that in HTML4 and XHTML1, the only methods a364-form can submit to the server are ``GET`` and ``POST``. But with JavaScript365-and future HTML standards you can use the other methods as well. Furthermore366-HTTP has become quite popular lately and browsers are no longer the only367-clients that are using HTTP. For instance, many revision control systems368-use it.369-314 .. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt315 316 Static Files317 ------------520 unmodified lines