Improve Routing section
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Edited the entire section for clarity and concision. I rewrote sentences to make them shorter and to reduce ambiguity. Added a code sample to show the path converter type Removed the HTTP method overview. Although it was well written, the overview wasn't necessary in the quickstart. Readers can easily find an overview elsewhere.
authored by Xephyr826 · committed by Xephyr826 · parent 5b83f11 · Browse files · 1 file·+33 added−117 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+33 added−117 removed
- other:+33 added−117 removed
Provenance
- Commit
dfb03c5- Tree
e10d2fb- Author
Xephyr826 <xephyr826@gmail.com>- Committer
Xephyr826 <xephyr826@gmail.com>- Parent
5b83f11
1 file changed+33 added−117 removed
modified:docs/quickstart.rst+33 added-117 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 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. 163 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::164+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::165 166 @app.route('/')167 def index():168 return 'Index Page'1 unmodified line170 @app.route('/hello')171 def hello():172 return 'Hello, World'173 179-But there is more to it! You can make certain parts of the URL dynamic and180-attach multiple rules to a function.174+You can do more! You can make parts of the URL dynamic and attach multiple rules to a function.175 176 Variable Rules177 ``````````````178 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::179+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::180 181 @app.route('/user/<username>')182 def show_user_profile(username):183 # show the user profile for that user3 unmodified lines187 def show_post(post_id):188 # show the post with the given id, the id is an integer189 return 'Post %d' % post_id190 200-The following converters exist:191+ @app.route('/path/<path:subpath>')192+ def show_subpath(subpath):193+ # show the subpath after /path/194+ return 'Subpath %s' % subpath195 196+Converter types:197+198 =========== ===============================================203-`string` accepts any text without a slash (the default)199+`string` (default) accepts any text without a slash200 `int` accepts integers205-`float` like ``int`` but for floating point values206-`path` like the default but also accepts slashes201+`float` accepts floating point values202+`path` like `string` but also accepts slashes203 `any` matches one of the items provided204 `uuid` accepts UUID strings205 =========== ===============================================206 207 .. admonition:: Unique URLs / Redirection Behavior208 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.209+ 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.210 211 Take these two rules::212 213 @app.route('/projects/')3 unmodified lines217 @app.route('/about')218 def about():219 return 'The about page'220 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.221+ 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.222 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.223+ 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.224 225 This behavior allows relative URLs to continue working even if the trailing226 slash is omitted, consistent with how Apache and other servers work. Also,227 the URLs will stay unique, which helps search engines avoid indexing the4 unmodified lines232 233 URL Building234 ````````````235 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::236+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.237 238+Why would you want to build URLs using the URL reversing function239+:func:`~flask.url_for` instead of hard-coding them into your templates? Three good reasons:240+241+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.242+2. URL building handles escaping of special characters and Unicode data transparently.243+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.244+245+246+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`.247+248+Example::249+250 >>> from flask import Flask, url_for251 >>> app = Flask(__name__)252 >>> @app.route('/')253 ... def index(): pass14 unmodified lines268 /login269 /login?next=/270 /user/John%20Doe271 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-282-Why would you want to build URLs using the URL reversing function283-:func:`~flask.url_for` instead of hard-coding them into your templates?284-There are three good reasons for this:285-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.294-295-272 HTTP Methods273 ````````````274 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::275+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::276 304- from flask import request305-277 @app.route('/login', methods=['GET', 'POST'])278 def login():279 if request.method == 'POST':309- return do_the_login()280+ do_the_login()281 else:311- return show_the_login_form()282+ show_the_login_form()283 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.284+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.285 320-You have no idea what an HTTP method is? Worry not, here is a quick321-introduction to HTTP methods and why they matter:322-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:326-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.330-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.338-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.344-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.354-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-286 .. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt287 288 Static Files289 ------------520 unmodified lines