quickstart.rst
This file
Path
docs/quickstart.rst
861 lines · 31.6 KiB
Last changed by
Add cookie size limit note to sessions section.Ron DuPlainbefore adoptiondfd3ef6
History of this fileTake it
The walk stopped after 200 commits: lines older than a070b4f point at it.
Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 1–5why, one step back1.. _quickstart:23Quickstart4==========5more editorial workOri Livnehbefore adoptiondf19ee9
lines 6–8why, one step back6Eager to get started? This page gives a good introduction to Flask. It7assumes you already have Flask installed. If you do not, head over to the8:ref:`installation` section.Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 9–25why, one step back91011A Minimal Application12---------------------1314A minimal Flask application looks something like this::1516 from flask import Flask17 app = Flask(__name__)1819 @app.route('/')20 def hello_world():21 return 'Hello World!'2223 if __name__ == '__main__':24 app.run()25more editorial workOri Livnehbefore adoptiondf19ee9
lines 26–28why, one step back26Just save it as `hello.py` (or something similar) and run it with your Python27interpreter. Make sure to not call your application `flask.py` because this28would conflict with Flask itself.Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 29–34why, one step back2930::3132 $ python hello.py33 * Running on http://127.0.0.1:5000/34more editorial workOri Livnehbefore adoptiondf19ee9
lines 35–36why, one step back35Now head over to `http://127.0.0.1:5000/ <http://127.0.0.1:5000/>`_, and you36should see your hello world greeting.Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 37–41why, one step back3738So what did that code do?39401. First we imported the :class:`~flask.Flask` class. An instance of this41 class will be our WSGI application. The first argument is the name ofmore editorial workOri Livnehbefore adoptiondf19ee9
lines 42–58why, one step back42 the application's module. If you are using a single module (as in this43 example), you should use `__name__` because depending on if it's started as44 application or imported as module the name will be different (``'__main__'``45 versus the actual import name). For more information, have a look at the46 :class:`~flask.Flask` documentation.472. Next we create an instance of this class. We pass it the name of the module48 or package. This is needed so that Flask knows where to look for templates,49 static files, and so on.503. We then use the :meth:`~flask.Flask.route` decorator to tell Flask what URL51 should trigger our function.524. The function is given a name which is also used to generate URLs for that53 particular function, and returns the message we want to display in the54 user's browser.555. Finally we use the :meth:`~flask.Flask.run` function to run the local server56 with our application. The ``if __name__ == '__main__':`` makes sure the57 server only runs if the script is executed directly from the Python58 interpreter and not used as imported module.Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 59–65why, one step back5960To stop the server, hit control-C.6162.. _public-server:6364.. admonition:: Externally Visible Server65Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c
line 66why, one step back66 If you run the server you will notice that the server is only accessibleMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 67–68why, one step back67 from your own computer, not from any other in the network. This is the68 default because in debugging mode a user of the application can executeMerge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c
line 69why, one step back69 arbitrary Python code on your computer.Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
line 70why, one step back70Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c
lines 71–73why, one step back71 If you have `debug` disabled or trust the users on your network, you can72 make the server publicly available simply by changing the call of the73 :meth:`~flask.Flask.run` method to look like this::Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 74–76why, one step back7475 app.run(host='0.0.0.0')76more editorial workOri Livnehbefore adoptiondf19ee9
line 77why, one step back77 This tells your operating system to listen on all public IPs.Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 78–84why, one step back787980Debug Mode81----------8283The :meth:`~flask.Flask.run` method is nice to start a local84development server, but you would have to restart it manually after eachMerge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c
lines 85–87why, one step back85change to your code. That is not very nice and Flask can do better. If86you enable debug support the server will reload itself on code changes,87and it will also provide you with a helpful debugger if things go wrong.Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 88–94why, one step back8889There are two ways to enable debugging. Either set that flag on the90application object::9192 app.debug = True93 app.run()94more editorial workOri Livnehbefore adoptiondf19ee9
line 95why, one step back95Or pass it as a parameter to run::Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 96–98why, one step back9697 app.run(debug=True)98more editorial workOri Livnehbefore adoptiondf19ee9
line 99why, one step back99Both methods have the exact same effect.Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 100–104why, one step back100101.. admonition:: Attention102103 Even though the interactive debugger does not work in forking environments104 (which makes it nearly impossible to use on production servers), it stillmore editorial workOri Livnehbefore adoptiondf19ee9
lines 105–106why, one step back105 allows the execution of arbitrary code. This makes it a major security risk106 and therefore it **must never be used on production machines**.Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 107–116why, one step back107108Screenshot of the debugger in action:109110.. image:: _static/debugger.png111 :align: center112 :class: screenshot113 :alt: screenshot of debugger in action114115.. admonition:: Working With Other Debuggers116more editorial workOri Livnehbefore adoptiondf19ee9
lines 117–118why, one step back117 Debuggers interfere with each other.118 That said, you may still wish to use the debugger in a tool of your choice.Documentation on how to use external debuggers like eclipse/aptanaSundar Ramanbefore adoption9469260
lines 119–124why, one step back119 Flask provides the following options to manage the debug process:120121 * ``debug`` - whether to enable debug mode and catch exceptinos122 * ``use_debugger`` - whether to use the internal Flask debugger123 * ``use_reloader`` - whether to reload and fork the process on exception124Add tiny doc touchups.Ron DuPlainbefore adoptioned40eac
line 125why, one step back125 ``debug`` must be True (i.e., exceptions must be caught) in order for theDocumentation on how to use external debuggers like eclipse/aptanaSundar Ramanbefore adoption9469260
lines 126–127why, one step back126 other two options to have any value.127more editorial workOri Livnehbefore adoptiondf19ee9
line 128why, one step back128 If you're using Aptana/Eclipse for debugging you'll need to set bothDocumentation on how to use external debuggers like eclipse/aptanaSundar Ramanbefore adoption9469260
lines 129–130why, one step back129 ``use_debugger`` and ``use_reloader`` to False.130more editorial workOri Livnehbefore adoptiondf19ee9
line 131why, one step back131 A possible useful pattern for configuration is to set the following in yourDocumentation on how to use external debuggers like eclipse/aptanaSundar Ramanbefore adoption9469260
lines 132–150why, one step back132 config.yaml (change the block as approriate for your application, of course)::133134 FLASK:135 DEBUG: True136 DEBUG_WITH_APTANA: True137138 Then in your application's entry-point (main.py), you could have something like::139140 if __name__ == "__main__":141 # To allow aptana to receive errors, set use_debugger=False142 app = create_app(config="config.yaml")143144 if app.debug: use_debugger = True145 try:146 # Disable Flask's debugger if external debugger is requested147 use_debugger = not(app.config.get('DEBUG_WITH_APTANA'))148 except:149 pass150 app.run(use_debugger=use_debugger, debug=app.debug, use_reloader=use_debugger, host='0.0.0.0')Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 151–156why, one step back151152153Routing154-------155156Modern web applications have beautiful URLs. This helps people rememberMerge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c
line 157why, one step back157the URLs, which is especially handy for applications that are used fromMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 158–161why, one step back158mobile devices with slower network connections. If the user can directly159go to the desired page without having to hit the index page it is more160likely they will like the page and come back next time.161more editorial workOri Livnehbefore adoptiondf19ee9
lines 162–163why, one step back162As you have seen above, the :meth:`~flask.Flask.route` decorator is used to163bind a function to a URL. Here are some basic examples::Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 164–172why, one step back164165 @app.route('/')166 def index():167 return 'Index Page'168169 @app.route('/hello')170 def hello():171 return 'Hello World'172more editorial workOri Livnehbefore adoptiondf19ee9
lines 173–174why, one step back173But there is more to it! You can make certain parts of the URL dynamic and174attach multiple rules to a function.Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 175–179why, one step back175176Variable Rules177``````````````178179To add variable parts to a URL you can mark these special sections asmore editorial workOri Livnehbefore adoptiondf19ee9
lines 180–182why, one step back180``<variable_name>``. Such a part is then passed as keyword argument to your181function. Optionally a converter can be specified by specifying a rule with182``<converter:variable_name>``. Here are some nice examples::Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 183–186why, one step back183184 @app.route('/user/<username>')185 def show_user_profile(username):186 # show the user profile for that userImproved doc exaples. This fixes #370 and #371.Armin Ronacherbefore adoption065afe5
line 187why, one step back187 return 'User %s' % usernameMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 188–191why, one step back188189 @app.route('/post/<int:post_id>')190 def show_post(post_id):191 # show the post with the given id, the id is an integerImproved doc exaples. This fixes #370 and #371.Armin Ronacherbefore adoption065afe5
line 192why, one step back192 return 'Post %d' % post_idMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 193–203why, one step back193194The following converters exist:195196=========== ===========================================197`int` accepts integers198`float` like `int` but for floating point values199`path` like the default but also accepts slashes200=========== ===========================================201202.. admonition:: Unique URLs / Redirection Behaviour203more editorial workOri Livnehbefore adoptiondf19ee9
lines 204–206why, one step back204 Flask's URL rules are based on Werkzeug's routing module. The idea behind205 that module is to ensure beautiful and unique also unique URLs based on206 precedents laid down by Apache and earlier HTTP servers.Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 207–211why, one step back207208 Take these two rules::209210 @app.route('/projects/')211 def projects():Improved doc exaples. This fixes #370 and #371.Armin Ronacherbefore adoption065afe5
line 212why, one step back212 return 'The project page'Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 213–215why, one step back213214 @app.route('/about')215 def about():Improved doc exaples. This fixes #370 and #371.Armin Ronacherbefore adoption065afe5
line 216why, one step back216 return 'The about page'Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
line 217why, one step back217more editorial workOri Livnehbefore adoptiondf19ee9
lines 218–222why, one step back218 Though they look rather similar, they differ in their use of the trailing219 slash in the URL *definition*. In the first case, the canonical URL for the220 `projects` endpoint has a trailing slash. In that sense, it is similar to221 a folder on a file system. Accessing it without a trailing slash will cause222 Flask to redirect to the canonical URL with the trailing slash.Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
line 223why, one step back223more editorial workOri Livnehbefore adoptiondf19ee9
lines 224–226why, one step back224 In the second case, however, the URL is defined without a trailing slash,225 rather like the pathname of a file on UNIX-like systems. Accessing the URL226 with a trailing slash will produce a 404 "Not Found" error.Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
line 227why, one step back227more editorial workOri Livnehbefore adoptiondf19ee9
lines 228–231why, one step back228 This behavior allows relative URLs to continue working if users access the229 page when they forget a trailing slash, consistent with how with how Apache230 and other servers work. Also, the URLs will stay unique, which helps search231 engines avoid indexing the same page twice.Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 232–238why, one step back232233234.. _url-building:235236URL Building237````````````238more editorial workOri Livnehbefore adoptiondf19ee9
line 239why, one step back239If it can match URLs, can Flask also generate them? Of course it can. ToMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
line 240why, one step back240build a URL to a specific function you can use the :func:`~flask.url_for`more editorial workOri Livnehbefore adoptiondf19ee9
lines 241–244why, one step back241function. It accepts the name of the function as first argument and a number242of keyword arguments, each corresponding to the variable part of the URL rule.243Unknown variable parts are appended to the URL as query parameters. Here are244some examples:Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 245–267why, one step back245246>>> from flask import Flask, url_for247>>> app = Flask(__name__)248>>> @app.route('/')249... def index(): pass250...251>>> @app.route('/login')252... def login(): pass253...254>>> @app.route('/user/<username>')255... def profile(username): pass256...257>>> with app.test_request_context():258... print url_for('index')259... print url_for('login')260... print url_for('login', next='/')261... print url_for('profile', username='John Doe')262...263/264/login265/login?next=/266/user/John%20Doe267more editorial workOri Livnehbefore adoptiondf19ee9
lines 268–271why, one step back268(This also uses the :meth:`~flask.Flask.test_request_context` method, explained269below. It tells Flask to behave as though it is handling a request, even270though were are interacting with it through a Python shell. Have a look at the271explanation below. :ref:`context-locals`).Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
line 272why, one step back272more editorial workOri Livnehbefore adoptiondf19ee9
line 273why, one step back273Why would you want to build URLs instead of hard-coding them into yourMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 274–275why, one step back274templates? There are three good reasons for this:275more editorial workOri Livnehbefore adoptiondf19ee9
lines 276–278why, one step back2761. Reversing is often more descriptive than hard-coding the URLs. More277 importantly, it allows you to change URLs in one go, without having to278 remember to change URLs all over the place.Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
line 279why, one step back2792. URL building will handle escaping of special characters and Unicodemore editorial workOri Livnehbefore adoptiondf19ee9
lines 280–283why, one step back280 data transparently for you, so you don't have to deal with them.2813. If your application is placed outside the URL root (say, in282 ``/myapplication`` instead of ``/``), :func:`~flask.url_for` will handle283 that properly for you.Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 284–288why, one step back284285286HTTP Methods287````````````288more editorial workOri Livnehbefore adoptiondf19ee9
lines 289–291why, one step back289HTTP (the protocol web applications are speaking) knows different methods for290accessing URLs. By default, a route only answers to `GET` requests, but that291can be changed by providing the `methods` argument to theMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 292–302why, one step back292:meth:`~flask.Flask.route` decorator. Here are some examples::293294 @app.route('/login', methods=['GET', 'POST'])295 def login():296 if request.method == 'POST':297 do_the_login()298 else:299 show_the_login_form()300301If `GET` is present, `HEAD` will be added automatically for you. You302don't have to deal with that. It will also make sure that `HEAD` requestsMerge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c
line 303why, one step back303are handled as the `HTTP RFC`_ (the document describing the HTTPMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
line 304why, one step back304protocol) demands, so you can completely ignore that part of the HTTPMerge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c
lines 305–306why, one step back305specification. Likewise, as of Flask 0.6, `OPTIONS` is implemented for you306automatically as well.Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 307–329why, one step back307308You have no idea what an HTTP method is? Worry not, here is a quick309introduction to HTTP methods and why they matter:310311The HTTP method (also often called "the verb") tells the server what the312clients wants to *do* with the requested page. The following methods are313very common:314315`GET`316 The browser tells the server to just *get* the information stored on317 that page and send it. This is probably the most common method.318319`HEAD`320 The browser tells the server to get the information, but it is only321 interested in the *headers*, not the content of the page. An322 application is supposed to handle that as if a `GET` request was323 received but to not deliver the actual content. In Flask you don't324 have to deal with that at all, the underlying Werkzeug library handles325 that for you.326327`POST`328 The browser tells the server that it wants to *post* some new329 information to that URL and that the server must ensure the data isMerge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c
lines 330–331why, one step back330 stored and only stored once. This is how HTML forms usually331 transmit data to the server.Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 332–335why, one step back332333`PUT`334 Similar to `POST` but the server might trigger the store procedure335 multiple times by overwriting the old values more than once. Now youMerge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c
lines 336–337why, one step back336 might be asking why this is useful, but there are some good reasons337 to do it this way. Consider that the connection is lost duringMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 338–362why, one step back338 transmission: in this situation a system between the browser and the339 server might receive the request safely a second time without breaking340 things. With `POST` that would not be possible because it must only341 be triggered once.342343`DELETE`344 Remove the information at the given location.345346`OPTIONS`347 Provides a quick way for a client to figure out which methods are348 supported by this URL. Starting with Flask 0.6, this is implemented349 for you automatically.350351Now the interesting part is that in HTML4 and XHTML1, the only methods a352form can submit to the server are `GET` and `POST`. But with JavaScript353and future HTML standards you can use the other methods as well. Furthermore354HTTP has become quite popular lately and browsers are no longer the only355clients that are using HTTP. For instance, many revision control system356use it.357358.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt359360Static Files361------------362Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c
line 363why, one step back363Dynamic web applications also need static files. That's usually whereMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 364–368why, one step back364the CSS and JavaScript files are coming from. Ideally your web server is365configured to serve them for you, but during development Flask can do that366as well. Just create a folder called `static` in your package or next to367your module and it will be available at `/static` on the application.368Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c
line 369why, one step back369To generate URLs that part of the URL, use the special ``'static'`` URLMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 370–384why, one step back370name::371372 url_for('static', filename='style.css')373374The file has to be stored on the filesystem as ``static/style.css``.375376Rendering Templates377-------------------378379Generating HTML from within Python is not fun, and actually pretty380cumbersome because you have to do the HTML escaping on your own to keep381the application secure. Because of that Flask configures the `Jinja2382<http://jinja.pocoo.org/2/>`_ template engine for you automatically.383384To render a template you can use the :func:`~flask.render_template`Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c
line 385why, one step back385method. All you have to do is provide the name of the template and theMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 386–396why, one step back386variables you want to pass to the template engine as keyword arguments.387Here's a simple example of how to render a template::388389 from flask import render_template390391 @app.route('/hello/')392 @app.route('/hello/<name>')393 def hello(name=None):394 return render_template('hello.html', name=name)395396Flask will look for templates in the `templates` folder. So if yourMerge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c
line 397why, one step back397application is a module, this folder is next to that module, if it's aMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 398–437why, one step back398package it's actually inside your package:399400**Case 1**: a module::401402 /application.py403 /templates404 /hello.html405406**Case 2**: a package::407408 /application409 /__init__.py410 /templates411 /hello.html412413For templates you can use the full power of Jinja2 templates. Head over414to the the official `Jinja2 Template Documentation415<http://jinja.pocoo.org/2/documentation/templates>`_ for more information.416417Here is an example template:418419.. sourcecode:: html+jinja420421 <!doctype html>422 <title>Hello from Flask</title>423 {% if name %}424 <h1>Hello {{ name }}!</h1>425 {% else %}426 <h1>Hello World!</h1>427 {% endif %}428429Inside templates you also have access to the :class:`~flask.request`,430:class:`~flask.session` and :class:`~flask.g` [#]_ objects431as well as the :func:`~flask.get_flashed_messages` function.432433Templates are especially useful if inheritance is used. If you want to434know how that works, head over to the :ref:`template-inheritance` pattern435documentation. Basically template inheritance makes it possible to keep436certain elements on each page (like header, navigation and footer).437Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c
line 438why, one step back438Automatic escaping is enabled, so if `name` contains HTML it will be escapedMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
line 439why, one step back439automatically. If you can trust a variable and you know that it will beMerge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c
line 440why, one step back440safe HTML (for example because it came from a module that converts wikiMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 441–474why, one step back441markup to HTML) you can mark it as safe by using the442:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the443template. Head over to the Jinja 2 documentation for more examples.444445Here is a basic introduction to how the :class:`~jinja2.Markup` class works:446447>>> from flask import Markup448>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'449Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')450>>> Markup.escape('<blink>hacker</blink>')451Markup(u'<blink>hacker</blink>')452>>> Markup('<em>Marked up</em> » HTML').striptags()453u'Marked up \xbb HTML'454455.. versionchanged:: 0.5456457 Autoescaping is no longer enabled for all templates. The following458 extensions for templates trigger autoescaping: ``.html``, ``.htm``,459 ``.xml``, ``.xhtml``. Templates loaded from a string will have460 autoescaping disabled.461462.. [#] Unsure what that :class:`~flask.g` object is? It's something in which463 you can store information for your own needs, check the documentation of464 that object (:class:`~flask.g`) and the :ref:`sqlite3` for more465 information.466467468Accessing Request Data469----------------------470471For web applications it's crucial to react to the data a client sent to472the server. In Flask this information is provided by the global473:class:`~flask.request` object. If you have some experience with Python474you might be wondering how that object can be global and how FlaskMerge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c
line 475why, one step back475manages to still be threadsafe. The answer is context locals:Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 476–492why, one step back476477478.. _context-locals:479480Context Locals481``````````````482483.. admonition:: Insider Information484485 If you want to understand how that works and how you can implement486 tests with context locals, read this section, otherwise just skip it.487488Certain objects in Flask are global objects, but not of the usual kind.489These objects are actually proxies to objects that are local to a specific490context. What a mouthful. But that is actually quite easy to understand.491492Imagine the context being the handling thread. A request comes in and theMerge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c
lines 493–495why, one step back493web server decides to spawn a new thread (or something else, the494underlying object is capable of dealing with concurrency systems other495than threads). When Flask starts its internal request handling itMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 496–497why, one step back496figures out that the current thread is the active context and binds the497current application and the WSGI environments to that context (thread).Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c
line 498why, one step back498It does that in an intelligent way so that one application can invoke anotherMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 499–501why, one step back499application without breaking.500501So what does this mean to you? Basically you can completely ignore thatMerge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c
lines 502–503why, one step back502this is the case unless you are doing something like unit testing. You503will notice that code which depends on a request object will suddenly breakMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 504–505why, one step back504because there is no request object. The solution is creating a request505object yourself and binding it to the context. The easiest solution forMerge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c
line 506why, one step back506unit testing is to use the :meth:`~flask.Flask.test_request_context`Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 507–620why, one step back507context manager. In combination with the `with` statement it will bind a508test request so that you can interact with it. Here is an example::509510 from flask import request511512 with app.test_request_context('/hello', method='POST'):513 # now you can do something with the request until the514 # end of the with block, such as basic assertions:515 assert request.path == '/hello'516 assert request.method == 'POST'517518The other possibility is passing a whole WSGI environment to the519:meth:`~flask.Flask.request_context` method::520521 from flask import request522523 with app.request_context(environ):524 assert request.method == 'POST'525526The Request Object527``````````````````528529The request object is documented in the API section and we will not cover530it here in detail (see :class:`~flask.request`). Here is a broad overview of531some of the most common operations. First of all you have to import it from532the `flask` module::533534 from flask import request535536The current request method is available by using the537:attr:`~flask.request.method` attribute. To access form data (data538transmitted in a `POST` or `PUT` request) you can use the539:attr:`~flask.request.form` attribute. Here is a full example of the two540attributes mentioned above::541542 @app.route('/login', methods=['POST', 'GET'])543 def login():544 error = None545 if request.method == 'POST':546 if valid_login(request.form['username'],547 request.form['password']):548 return log_the_user_in(request.form['username'])549 else:550 error = 'Invalid username/password'551 # this is executed if the request method was GET or the552 # credentials were invalid553554What happens if the key does not exist in the `form` attribute? In that555case a special :exc:`KeyError` is raised. You can catch it like a556standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request557error page is shown instead. So for many situations you don't have to558deal with that problem.559560To access parameters submitted in the URL (``?key=value``) you can use the561:attr:`~flask.request.args` attribute::562563 searchword = request.args.get('q', '')564565We recommend accessing URL parameters with `get` or by catching the566`KeyError` because users might change the URL and presenting them a 400567bad request page in that case is not user friendly.568569For a full list of methods and attributes of the request object, head over570to the :class:`~flask.request` documentation.571572573File Uploads574````````````575576You can handle uploaded files with Flask easily. Just make sure not to577forget to set the ``enctype="multipart/form-data"`` attribute on your HTML578form, otherwise the browser will not transmit your files at all.579580Uploaded files are stored in memory or at a temporary location on the581filesystem. You can access those files by looking at the582:attr:`~flask.request.files` attribute on the request object. Each583uploaded file is stored in that dictionary. It behaves just like a584standard Python :class:`file` object, but it also has a585:meth:`~werkzeug.datastructures.FileStorage.save` method that allows you to store that586file on the filesystem of the server. Here is a simple example showing how587that works::588589 from flask import request590591 @app.route('/upload', methods=['GET', 'POST'])592 def upload_file():593 if request.method == 'POST':594 f = request.files['the_file']595 f.save('/var/www/uploads/uploaded_file.txt')596 ...597598If you want to know how the file was named on the client before it was599uploaded to your application, you can access the600:attr:`~werkzeug.datastructures.FileStorage.filename` attribute. However please keep in601mind that this value can be forged so never ever trust that value. If you602want to use the filename of the client to store the file on the server,603pass it through the :func:`~werkzeug.utils.secure_filename` function that604Werkzeug provides for you::605606 from flask import request607 from werkzeug import secure_filename608609 @app.route('/upload', methods=['GET', 'POST'])610 def upload_file():611 if request.method == 'POST':612 f = request.files['the_file']613 f.save('/var/www/uploads/' + secure_filename(f.filename))614 ...615616For some better examples, checkout the :ref:`uploading-files` pattern.617618Cookies619```````620Improved cookie documentationArmin Ronacherbefore adoption13005d7
lines 621–648why, one step back621To access cookies you can use the :attr:`~flask.Request.cookies`622attribute. To set cookies you can use the623:attr:`~flask.Response.set_cookie` method of response objects. The624:attr:`~flask.Request.cookies` attribute of request objects is a625dictionary with all the cookies the client transmits. If you want to use626sessions, do not use the cookies directly but instead use the627:ref:`sessions` in Flask that add some security on top of cookies for you.628629Reading cookies::630631 from flask import request632633 @app.route('/')634 def index():635 username = request.cookies.get('username')636 # use cookies.get(key) instead of cookies[key] to not get a637 # KeyError if the cookie is missing.638639Storing cookies::640641 from flask import make_response642643 @app.route('/')644 def index():645 resp = make_response(render_template(...))646 resp.set_cookie('username', 'the username')647 return resp648Simple documentation corrections, mostly typos.Craig Dennisbefore adoption75050d4
line 649why, one step back649Note that cookies are set on response objects. Since you normallyImproved cookie documentationArmin Ronacherbefore adoption13005d7
lines 650–652why, one step back650just return strings from the view functions Flask will convert them into651response objects for you. If you explicitly want to do that you can use652the :meth:`~flask.make_response` function and then modify it.Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
line 653why, one step back653Updated the documentation to show how to set cookies for not yet existing responsesArmin Ronacherbefore adoptionb40af3c
lines 654–657why, one step back654Sometimes you might want to set a cookie at a point where the response655object does not exist yet. This is possible by utilizing the656:ref:`deferred-callbacks` pattern.657Extended quickstart docs for the headersArmin Ronacherbefore adoption5b16532
line 658why, one step back658For this also see :ref:`about-responses`.Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 659–694why, one step back659660Redirects and Errors661--------------------662663To redirect a user to somewhere else you can use the664:func:`~flask.redirect` function. To abort a request early with an error665code use the :func:`~flask.abort` function. Here an example how this works::666667 from flask import abort, redirect, url_for668669 @app.route('/')670 def index():671 return redirect(url_for('login'))672673 @app.route('/login')674 def login():675 abort(401)676 this_is_never_executed()677678This is a rather pointless example because a user will be redirected from679the index to a page they cannot access (401 means access denied) but it680shows how that works.681682By default a black and white error page is shown for each error code. If683you want to customize the error page, you can use the684:meth:`~flask.Flask.errorhandler` decorator::685686 from flask import render_template687688 @app.errorhandler(404)689 def page_not_found(error):690 return render_template('page_not_found.html'), 404691692Note the ``404`` after the :func:`~flask.render_template` call. This693tells Flask that the status code of that page should be 404 which means694not found. By default 200 is assumed which translates to: all went well.Extended quickstart docs for the headersArmin Ronacherbefore adoption5b16532
lines 695–712why, one step back695696.. _about-responses:697698About Responses699---------------700701The return value from a view function is automatically converted into a702response object for you. If the return value is a string it's converted703into a response object with the string as response body, an ``200 OK``704error code and a ``text/html`` mimetype. The logic that Flask applies to705converting return values into response objects is as follows:7067071. If a response object of the correct type is returned it's directly708 returned from the view.7092. If it's a string, a response object is created with that data and the710 default parameters.7113. If a tuple is returned the response object is created by passing the712 tuple as arguments to the response object's constructor.Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c
lines 713–714why, one step back7134. If none of that works, Flask will assume the return value is a714 valid WSGI application and convert that into a response object.Extended quickstart docs for the headersArmin Ronacherbefore adoption5b16532
lines 715–737why, one step back715716If you want to get hold of the resulting response object inside the view717you can use the :func:`~flask.make_response` function.718719Imagine you have a view like this:720721.. sourcecode:: python722723 @app.errorhandler(404)724 def not_found(error):725 return render_template('error.html'), 404726727You just need to wrap the return expression with728:func:`~flask.make_response` and get the result object to modify it, then729return it:730731.. sourcecode:: python732733 @app.errorhandler(404)734 def not_found(error):735 resp = make_response(render_template('error.html'), 404)736 resp.headers['X-Something'] = 'A value'737 return respMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 738–743why, one step back738739.. _sessions:740741Sessions742--------743Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c
lines 744–745why, one step back744In addition to the request object there is also a second object called745:class:`~flask.session` which allows you to store information specific to aMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 746–784why, one step back746user from one request to the next. This is implemented on top of cookies747for you and signs the cookies cryptographically. What this means is that748the user could look at the contents of your cookie but not modify it,749unless they know the secret key used for signing.750751In order to use sessions you have to set a secret key. Here is how752sessions work::753754 from flask import Flask, session, redirect, url_for, escape, request755756 app = Flask(__name__)757758 @app.route('/')759 def index():760 if 'username' in session:761 return 'Logged in as %s' % escape(session['username'])762 return 'You are not logged in'763764 @app.route('/login', methods=['GET', 'POST'])765 def login():766 if request.method == 'POST':767 session['username'] = request.form['username']768 return redirect(url_for('index'))769 return '''770 <form action="" method="post">771 <p><input type=text name=username>772 <p><input type=submit value=Login>773 </form>774 '''775776 @app.route('/logout')777 def logout():778 # remove the username from the session if its there779 session.pop('username', None)780 return redirect(url_for('index'))781782 # set the secret key. keep this really secret:783 app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'784Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c
lines 785–786why, one step back785The :func:`~flask.escape` mentioned here does escaping for you if you are786not using the template engine (as in this example).Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 787–789why, one step back787788.. admonition:: How to generate good secret keys789Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c
line 790why, one step back790 The problem with random is that it's hard to judge what is truly random. AndMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 791–800why, one step back791 a secret key should be as random as possible. Your operating system792 has ways to generate pretty random stuff based on a cryptographic793 random generator which can be used to get such a key:794795 >>> import os796 >>> os.urandom(24)797 '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'798799 Just take that thing and copy/paste it into your code and you're done.800Add cookie size limit note to sessions section.Ron DuPlainbefore adoptiondfd3ef6
lines 801–807why, one step back801A note on cookie-based sessions: Flask will take the values you put into the802session object and serialize them into a cookie. If you are finding some803values do not persist across requests, cookies are indeed enabled, and you are804not getting a clear error message, check the size of the cookie in your page805responses compared to the size supported by web browsers.806807Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 808–814why, one step back808Message Flashing809----------------810811Good applications and user interfaces are all about feedback. If the user812does not get enough feedback they will probably end up hating the813application. Flask provides a really simple way to give feedback to a814user with the flashing system. The flashing system basically makes itMerge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c
lines 815–817why, one step back815possible to record a message at the end of a request and access it on the next816(and only the next) request. This is usually combined with a layout817template to expose the message.Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 818–829why, one step back818819To flash a message use the :func:`~flask.flash` method, to get hold of the820messages you can use :func:`~flask.get_flashed_messages` which is also821available in the templates. Check out the :ref:`message-flashing-pattern`822for a full example.823824Logging825-------826827.. versionadded:: 0.3828829Sometimes you might be in a situation where you deal with data thatMerge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c
lines 830–833why, one step back830should be correct, but actually is not. For example you may have some client-side831code that sends an HTTP request to the server but it's obviously832malformed. This might be caused by a user tampering with the data, or the833client code failing. Most of the time it's okay to reply with ``400 BadMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptiona070b4f
lines 834–861why, one step back834Request`` in that situation, but sometimes that won't do and the code has835to continue working.836837You may still want to log that something fishy happened. This is where838loggers come in handy. As of Flask 0.3 a logger is preconfigured for you839to use.840841Here are some example log calls::842843 app.logger.debug('A value for debugging')844 app.logger.warning('A warning occurred (%d apples)', 42)845 app.logger.error('An error occurred')846847The attached :attr:`~flask.Flask.logger` is a standard logging848:class:`~logging.Logger`, so head over to the official `logging849documentation <http://docs.python.org/library/logging.html>`_ for more850information.851852Hooking in WSGI Middlewares853---------------------------854855If you want to add a WSGI middleware to your application you can wrap the856internal WSGI application. For example if you want to use one of the857middlewares from the Werkzeug package to work around bugs in lighttpd, you858can do it like this::859860 from werkzeug.contrib.fixers import LighttpdCGIRootFix861 app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)