Skip to content
Myr

quickstart.rst

This file

Path

docs/quickstart.rst

855 lines · 31.2 KiB

Last changed by

Documentation on how to use external debuggers like eclipse/aptanaSundar Ramanbefore adoption9469260

History of this file

Take it

The walk stopped after 200 commits: lines older than e2fed6c point at it.

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 1–5why, one step back
1.. _quickstart:
23Quickstart4==========5

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

line 6why, one step back
6Eager to get started? This page gives a good introduction on how to get

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 7–20why, one step back
7started with Flask. This assumes you already have Flask installed. If
8you do not, head over to the :ref:`installation` section.91011A 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():

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

line 21why, one step back
21 return 'Hello World!'

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 22–41why, one step back
22
23 if __name__ == '__main__':24 app.run()2526Just save it as `hello.py` or something similar and run it with your27Python interpreter. Make sure to not call your application `flask.py`28because this would conflict with Flask itself.2930::3132 $ python hello.py33 * Running on http://127.0.0.1:5000/3435Head over to `http://127.0.0.1:5000/ <http://127.0.0.1:5000/>`_, you should36see your hello world greeting.3738So 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 of

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

lines 42–43why, one step back
42 the application's module. If you are using a single module (as in this example)
43 you should use `__name__` because depending on whether it's started as

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 44–45why, one step back
44 application or imported as module the name will be different
45 (``'__main__'`` versus the actual import name). For more information

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

line 46why, one step back
46 on this technique, have a look at the :class:`~flask.Flask` documentation.

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 47–50why, one step back
472. Next we create an instance of it. We pass it the name of the module /
48 package. This is needed so that Flask knows where it should look for49 templates, static files and so on.503. Then we use the :meth:`~flask.Flask.route` decorator to tell Flask

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

line 51why, one step back
51 which URL should trigger our function.

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 52–65why, one step back
524. The function then has a name which is also used to generate URLs to
53 that particular function, and returns the message we want to display in54 the user's browser.555. Finally we use the :meth:`~flask.Flask.run` function to run the56 local server with our application. The ``if __name__ == '__main__':``57 makes sure the server only runs if the script is executed directly from58 the Python interpreter and not used as imported module.5960To stop the server, hit control-C.6162.. _public-server:6364.. admonition:: Externally Visible Server65

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

line 66why, one step back
66 If you run the server you will notice that the server is only accessible

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 67–68why, one step back
67 from your own computer, not from any other in the network. This is the
68 default because in debugging mode a user of the application can execute

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

line 69why, one step back
69 arbitrary Python code on your computer.

Fixed another typoArmin Ronacherbefore adoptione2fed6c

line 70why, one step back
70

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

lines 71–73why, one step back
71 If you have `debug` disabled or trust the users on your network, you can
72 make the server publicly available simply by changing the call of the73 :meth:`~flask.Flask.run` method to look like this::

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 74–84why, one step back
74
75 app.run(host='0.0.0.0')7677 This tells your operating system to listen on a public IP.787980Debug Mode81----------8283The :meth:`~flask.Flask.run` method is nice to start a local84development server, but you would have to restart it manually after each

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

lines 85–87why, one step back
85change to your code. That is not very nice and Flask can do better. If
86you 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.

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 88–94why, one step back
88
89There are two ways to enable debugging. Either set that flag on the90application object::9192 app.debug = True93 app.run()94

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

line 95why, one step back
95Or pass it to `run`::

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 96–116why, one step back
96
97 app.run(debug=True)9899Both will have exactly the same effect.100101.. admonition:: Attention102103 Even though the interactive debugger does not work in forking environments104 (which makes it nearly impossible to use on production servers), it still105 allows the execution of arbitrary code. That makes it a major security106 risk and therefore it **must never be used on production machines**.107108Screenshot of the debugger in action:109110.. image:: _static/debugger.png111 :align: center112 :class: screenshot113 :alt: screenshot of debugger in action114115.. admonition:: Working With Other Debuggers116

Documentation on how to use external debuggers like eclipse/aptanaSundar Ramanbefore adoption9469260

lines 117–150why, one step back
117 Debuggers interfere with each other.
118 That said, you may still wish to use the debugger in a tool of your choice. 119 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 exception124125 ``debug`` must be True (i.e., exceptions must caught) in order for the 126 other two options to have any value.127128 If you're using Aptana/Eclipse for debugging you'll need to set both 129 ``use_debugger`` and ``use_reloader`` to False.130131 A possible useful pattern for configuration is to set the following in your 132 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')

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 151–156why, one step back
151
152153Routing154-------155156Modern web applications have beautiful URLs. This helps people remember

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

line 157why, one step back
157the URLs, which is especially handy for applications that are used from

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 158–186why, one step back
158mobile devices with slower network connections. If the user can directly
159go to the desired page without having to hit the index page it is more160likely they will like the page and come back next time.161162As you have seen above, the :meth:`~flask.Flask.route` decorator is used163to bind a function to a URL. Here are some basic examples::164165 @app.route('/')166 def index():167 return 'Index Page'168169 @app.route('/hello')170 def hello():171 return 'Hello World'172173But there is more to it! You can make certain parts of the URL dynamic174and attach multiple rules to a function.175176Variable Rules177``````````````178179To add variable parts to a URL you can mark these special sections as180``<variable_name>``. Such a part is then passed as keyword argument to181your function. Optionally a converter can be specified by specifying a182rule with ``<converter:variable_name>``. Here are some nice examples::183184 @app.route('/user/<username>')185 def show_user_profile(username):186 # show the user profile for that user

Improved doc exaples. This fixes #370 and #371.Armin Ronacherbefore adoption065afe5

line 187why, one step back
187 return 'User %s' % username

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 188–191why, one step back
188
189 @app.route('/post/<int:post_id>')190 def show_post(post_id):191 # show the post with the given id, the id is an integer

Improved doc exaples. This fixes #370 and #371.Armin Ronacherbefore adoption065afe5

line 192why, one step back
192 return 'Post %d' % post_id

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 193–204why, one step back
193
194The 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 Behaviour203204 Flask's URL rules are based on Werkzeug's routing module. The idea

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

lines 205–206why, one step back
205 behind that module is to ensure nice-looking and also unique URLs based
206 on behaviour coined by Apache and earlier servers.

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 207–211why, one step back
207
208 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 back
212 return 'The project page'

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 213–215why, one step back
213
214 @app.route('/about')215 def about():

Improved doc exaples. This fixes #370 and #371.Armin Ronacherbefore adoption065afe5

line 216why, one step back
216 return 'The about page'

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 217–223why, one step back
217
218 They look rather similar, the difference is the trailing slash in the219 URL *definition*. In the first case, the canonical URL for the220 `projects` endpoint has a trailing slash. It's similar to a folder in221 that sense. Accessing it without a trailing slash will cause Flask to222 redirect to the canonical URL with the trailing slash.223

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

line 224why, one step back
224 However, in the second case the URL is defined without a slash so it

Fixed another typoArmin Ronacherbefore adoptione2fed6c

line 225why, one step back
225 behaves similar to a file and accessing the URL with a trailing slash

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

line 226why, one step back
226 will result in a 404 error.

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 227–230why, one step back
227
228 Why is this? This allows relative URLs to continue working if users229 access the page when they forget a trailing slash. This behaviour is230 also consistent with how Apache and other servers work. Also, the URLs

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

line 231why, one step back
231 will stay unique which ensures search engines do not index the same page

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 232–271why, one step back
232 twice.
233234235.. _url-building:236237URL Building238````````````239240If it can match URLs, can it also generate them? Of course it can. To241build a URL to a specific function you can use the :func:`~flask.url_for`242function. It accepts the name of the function as first argument and a243number of keyword arguments, each corresponding to the variable part of244the URL rule. Unknown variable parts are appended to the URL as query245parameter. Here are some examples:246247>>> from flask import Flask, url_for248>>> app = Flask(__name__)249>>> @app.route('/')250... def index(): pass251...252>>> @app.route('/login')253... def login(): pass254...255>>> @app.route('/user/<username>')256... def profile(username): pass257...258>>> with app.test_request_context():259... print url_for('index')260... print url_for('login')261... print url_for('login', next='/')262... print url_for('profile', username='John Doe')263...264/265/login266/login?next=/267/user/John%20Doe268269(This also uses the :meth:`~flask.Flask.test_request_context` method270explained below. It basically tells Flask to think we are handling a271request even though we are not, we are in an interactive Python shell.

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

line 272why, one step back
272Have a look at the explanation below: :ref:`context-locals`.)

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 273–303why, one step back
273
274Why would you want to build URLs instead of hardcoding them in your275templates? There are three good reasons for this:2762771. reversing is often more descriptive than hardcoding the URLs. Also and278 more importantly you can change URLs in one go without having to change279 the URLs all over the place.2802. URL building will handle escaping of special characters and Unicode281 data transparently for you, you don't have to deal with that.2823. If your application is placed outside the URL root (so say in283 ``/myapplication`` instead of ``/``), :func:`~flask.url_for` will284 handle that properly for you.285286287HTTP Methods288````````````289290HTTP (the protocol web applications are speaking) knows different methods291to access URLs. By default a route only answers to `GET` requests, but292that can be changed by providing the `methods` argument to the293:meth:`~flask.Flask.route` decorator. Here are some examples::294295 @app.route('/login', methods=['GET', 'POST'])296 def login():297 if request.method == 'POST':298 do_the_login()299 else:300 show_the_login_form()301302If `GET` is present, `HEAD` will be added automatically for you. You303don't have to deal with that. It will also make sure that `HEAD` requests

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

line 304why, one step back
304are handled as the `HTTP RFC`_ (the document describing the HTTP

Fixed another typoArmin Ronacherbefore adoptione2fed6c

line 305why, one step back
305protocol) demands, so you can completely ignore that part of the HTTP

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

lines 306–307why, one step back
306specification. Likewise, as of Flask 0.6, `OPTIONS` is implemented for you
307automatically as well.

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 308–330why, one step back
308
309You have no idea what an HTTP method is? Worry not, here is a quick310introduction to HTTP methods and why they matter:311312The HTTP method (also often called "the verb") tells the server what the313clients wants to *do* with the requested page. The following methods are314very common:315316`GET`317 The browser tells the server to just *get* the information stored on318 that page and send it. This is probably the most common method.319320`HEAD`321 The browser tells the server to get the information, but it is only322 interested in the *headers*, not the content of the page. An323 application is supposed to handle that as if a `GET` request was324 received but to not deliver the actual content. In Flask you don't325 have to deal with that at all, the underlying Werkzeug library handles326 that for you.327328`POST`329 The browser tells the server that it wants to *post* some new330 information to that URL and that the server must ensure the data is

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

lines 331–332why, one step back
331 stored and only stored once. This is how HTML forms usually
332 transmit data to the server.

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 333–336why, one step back
333
334`PUT`335 Similar to `POST` but the server might trigger the store procedure336 multiple times by overwriting the old values more than once. Now you

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

lines 337–338why, one step back
337 might be asking why this is useful, but there are some good reasons
338 to do it this way. Consider that the connection is lost during

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 339–363why, one step back
339 transmission: in this situation a system between the browser and the
340 server might receive the request safely a second time without breaking341 things. With `POST` that would not be possible because it must only342 be triggered once.343344`DELETE`345 Remove the information at the given location.346347`OPTIONS`348 Provides a quick way for a client to figure out which methods are349 supported by this URL. Starting with Flask 0.6, this is implemented350 for you automatically.351352Now the interesting part is that in HTML4 and XHTML1, the only methods a353form can submit to the server are `GET` and `POST`. But with JavaScript354and future HTML standards you can use the other methods as well. Furthermore355HTTP has become quite popular lately and browsers are no longer the only356clients that are using HTTP. For instance, many revision control system357use it.358359.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt360361Static Files362------------363

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

line 364why, one step back
364Dynamic web applications also need static files. That's usually where

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 365–369why, one step back
365the CSS and JavaScript files are coming from. Ideally your web server is
366configured to serve them for you, but during development Flask can do that367as well. Just create a folder called `static` in your package or next to368your module and it will be available at `/static` on the application.369

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

line 370why, one step back
370To generate URLs that part of the URL, use the special ``'static'`` URL

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 371–385why, one step back
371name::
372373 url_for('static', filename='style.css')374375The file has to be stored on the filesystem as ``static/style.css``.376377Rendering Templates378-------------------379380Generating HTML from within Python is not fun, and actually pretty381cumbersome because you have to do the HTML escaping on your own to keep382the application secure. Because of that Flask configures the `Jinja2383<http://jinja.pocoo.org/2/>`_ template engine for you automatically.384385To render a template you can use the :func:`~flask.render_template`

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

line 386why, one step back
386method. All you have to do is provide the name of the template and the

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 387–397why, one step back
387variables you want to pass to the template engine as keyword arguments.
388Here's a simple example of how to render a template::389390 from flask import render_template391392 @app.route('/hello/')393 @app.route('/hello/<name>')394 def hello(name=None):395 return render_template('hello.html', name=name)396397Flask will look for templates in the `templates` folder. So if your

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

line 398why, one step back
398application is a module, this folder is next to that module, if it's a

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 399–438why, one step back
399package it's actually inside your package:
400401**Case 1**: a module::402403 /application.py404 /templates405 /hello.html406407**Case 2**: a package::408409 /application410 /__init__.py411 /templates412 /hello.html413414For templates you can use the full power of Jinja2 templates. Head over415to the the official `Jinja2 Template Documentation416<http://jinja.pocoo.org/2/documentation/templates>`_ for more information.417418Here is an example template:419420.. sourcecode:: html+jinja421422 <!doctype html>423 <title>Hello from Flask</title>424 {% if name %}425 <h1>Hello {{ name }}!</h1>426 {% else %}427 <h1>Hello World!</h1>428 {% endif %}429430Inside templates you also have access to the :class:`~flask.request`,431:class:`~flask.session` and :class:`~flask.g` [#]_ objects432as well as the :func:`~flask.get_flashed_messages` function.433434Templates are especially useful if inheritance is used. If you want to435know how that works, head over to the :ref:`template-inheritance` pattern436documentation. Basically template inheritance makes it possible to keep437certain elements on each page (like header, navigation and footer).438

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

line 439why, one step back
439Automatic escaping is enabled, so if `name` contains HTML it will be escaped

Fixed another typoArmin Ronacherbefore adoptione2fed6c

line 440why, one step back
440automatically. If you can trust a variable and you know that it will be

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

line 441why, one step back
441safe HTML (for example because it came from a module that converts wiki

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 442–475why, one step back
442markup to HTML) you can mark it as safe by using the
443:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the444template. Head over to the Jinja 2 documentation for more examples.445446Here is a basic introduction to how the :class:`~jinja2.Markup` class works:447448>>> from flask import Markup449>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'450Markup(u'<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')451>>> Markup.escape('<blink>hacker</blink>')452Markup(u'&lt;blink&gt;hacker&lt;/blink&gt;')453>>> Markup('<em>Marked up</em> &raquo; HTML').striptags()454u'Marked up \xbb HTML'455456.. versionchanged:: 0.5457458 Autoescaping is no longer enabled for all templates. The following459 extensions for templates trigger autoescaping: ``.html``, ``.htm``,460 ``.xml``, ``.xhtml``. Templates loaded from a string will have461 autoescaping disabled.462463.. [#] Unsure what that :class:`~flask.g` object is? It's something in which464 you can store information for your own needs, check the documentation of465 that object (:class:`~flask.g`) and the :ref:`sqlite3` for more466 information.467468469Accessing Request Data470----------------------471472For web applications it's crucial to react to the data a client sent to473the server. In Flask this information is provided by the global474:class:`~flask.request` object. If you have some experience with Python475you might be wondering how that object can be global and how Flask

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

line 476why, one step back
476manages to still be threadsafe. The answer is context locals:

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 477–493why, one step back
477
478479.. _context-locals:480481Context Locals482``````````````483484.. admonition:: Insider Information485486 If you want to understand how that works and how you can implement487 tests with context locals, read this section, otherwise just skip it.488489Certain objects in Flask are global objects, but not of the usual kind.490These objects are actually proxies to objects that are local to a specific491context. What a mouthful. But that is actually quite easy to understand.492493Imagine the context being the handling thread. A request comes in and the

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

lines 494–496why, one step back
494web server decides to spawn a new thread (or something else, the
495underlying object is capable of dealing with concurrency systems other496than threads). When Flask starts its internal request handling it

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 497–498why, one step back
497figures out that the current thread is the active context and binds the
498current application and the WSGI environments to that context (thread).

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

line 499why, one step back
499It does that in an intelligent way so that one application can invoke another

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 500–502why, one step back
500application without breaking.
501502So what does this mean to you? Basically you can completely ignore that

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

lines 503–504why, one step back
503this is the case unless you are doing something like unit testing. You
504will notice that code which depends on a request object will suddenly break

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 505–506why, one step back
505because there is no request object. The solution is creating a request
506object yourself and binding it to the context. The easiest solution for

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

line 507why, one step back
507unit testing is to use the :meth:`~flask.Flask.test_request_context`

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 508–621why, one step back
508context manager. In combination with the `with` statement it will bind a
509test request so that you can interact with it. Here is an example::510511 from flask import request512513 with app.test_request_context('/hello', method='POST'):514 # now you can do something with the request until the515 # end of the with block, such as basic assertions:516 assert request.path == '/hello'517 assert request.method == 'POST'518519The other possibility is passing a whole WSGI environment to the520:meth:`~flask.Flask.request_context` method::521522 from flask import request523524 with app.request_context(environ):525 assert request.method == 'POST'526527The Request Object528``````````````````529530The request object is documented in the API section and we will not cover531it here in detail (see :class:`~flask.request`). Here is a broad overview of532some of the most common operations. First of all you have to import it from533the `flask` module::534535 from flask import request536537The current request method is available by using the538:attr:`~flask.request.method` attribute. To access form data (data539transmitted in a `POST` or `PUT` request) you can use the540:attr:`~flask.request.form` attribute. Here is a full example of the two541attributes mentioned above::542543 @app.route('/login', methods=['POST', 'GET'])544 def login():545 error = None546 if request.method == 'POST':547 if valid_login(request.form['username'],548 request.form['password']):549 return log_the_user_in(request.form['username'])550 else:551 error = 'Invalid username/password'552 # this is executed if the request method was GET or the553 # credentials were invalid554555What happens if the key does not exist in the `form` attribute? In that556case a special :exc:`KeyError` is raised. You can catch it like a557standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request558error page is shown instead. So for many situations you don't have to559deal with that problem.560561To access parameters submitted in the URL (``?key=value``) you can use the562:attr:`~flask.request.args` attribute::563564 searchword = request.args.get('q', '')565566We recommend accessing URL parameters with `get` or by catching the567`KeyError` because users might change the URL and presenting them a 400568bad request page in that case is not user friendly.569570For a full list of methods and attributes of the request object, head over571to the :class:`~flask.request` documentation.572573574File Uploads575````````````576577You can handle uploaded files with Flask easily. Just make sure not to578forget to set the ``enctype="multipart/form-data"`` attribute on your HTML579form, otherwise the browser will not transmit your files at all.580581Uploaded files are stored in memory or at a temporary location on the582filesystem. You can access those files by looking at the583:attr:`~flask.request.files` attribute on the request object. Each584uploaded file is stored in that dictionary. It behaves just like a585standard Python :class:`file` object, but it also has a586:meth:`~werkzeug.datastructures.FileStorage.save` method that allows you to store that587file on the filesystem of the server. Here is a simple example showing how588that works::589590 from flask import request591592 @app.route('/upload', methods=['GET', 'POST'])593 def upload_file():594 if request.method == 'POST':595 f = request.files['the_file']596 f.save('/var/www/uploads/uploaded_file.txt')597 ...598599If you want to know how the file was named on the client before it was600uploaded to your application, you can access the601:attr:`~werkzeug.datastructures.FileStorage.filename` attribute. However please keep in602mind that this value can be forged so never ever trust that value. If you603want to use the filename of the client to store the file on the server,604pass it through the :func:`~werkzeug.utils.secure_filename` function that605Werkzeug provides for you::606607 from flask import request608 from werkzeug import secure_filename609610 @app.route('/upload', methods=['GET', 'POST'])611 def upload_file():612 if request.method == 'POST':613 f = request.files['the_file']614 f.save('/var/www/uploads/' + secure_filename(f.filename))615 ...616617For some better examples, checkout the :ref:`uploading-files` pattern.618619Cookies620```````621

Improved cookie documentationArmin Ronacherbefore adoption13005d7

lines 622–649why, one step back
622To access cookies you can use the :attr:`~flask.Request.cookies`
623attribute. To set cookies you can use the624:attr:`~flask.Response.set_cookie` method of response objects. The625:attr:`~flask.Request.cookies` attribute of request objects is a626dictionary with all the cookies the client transmits. If you want to use627sessions, do not use the cookies directly but instead use the628:ref:`sessions` in Flask that add some security on top of cookies for you.629630Reading cookies::631632 from flask import request633634 @app.route('/')635 def index():636 username = request.cookies.get('username')637 # use cookies.get(key) instead of cookies[key] to not get a638 # KeyError if the cookie is missing.639640Storing cookies::641642 from flask import make_response643644 @app.route('/')645 def index():646 resp = make_response(render_template(...))647 resp.set_cookie('username', 'the username')648 return resp649

Simple documentation corrections, mostly typos.Craig Dennisbefore adoption75050d4

line 650why, one step back
650Note that cookies are set on response objects. Since you normally

Improved cookie documentationArmin Ronacherbefore adoption13005d7

lines 651–653why, one step back
651just return strings from the view functions Flask will convert them into
652response objects for you. If you explicitly want to do that you can use653the :meth:`~flask.make_response` function and then modify it.

Fixed another typoArmin Ronacherbefore adoptione2fed6c

line 654why, one step back
654

Updated the documentation to show how to set cookies for not yet existing responsesArmin Ronacherbefore adoptionb40af3c

lines 655–658why, one step back
655Sometimes you might want to set a cookie at a point where the response
656object does not exist yet. This is possible by utilizing the657:ref:`deferred-callbacks` pattern.658

Extended quickstart docs for the headersArmin Ronacherbefore adoption5b16532

line 659why, one step back
659For this also see :ref:`about-responses`.

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 660–695why, one step back
660
661Redirects and Errors662--------------------663664To redirect a user to somewhere else you can use the665:func:`~flask.redirect` function. To abort a request early with an error666code use the :func:`~flask.abort` function. Here an example how this works::667668 from flask import abort, redirect, url_for669670 @app.route('/')671 def index():672 return redirect(url_for('login'))673674 @app.route('/login')675 def login():676 abort(401)677 this_is_never_executed()678679This is a rather pointless example because a user will be redirected from680the index to a page they cannot access (401 means access denied) but it681shows how that works.682683By default a black and white error page is shown for each error code. If684you want to customize the error page, you can use the685:meth:`~flask.Flask.errorhandler` decorator::686687 from flask import render_template688689 @app.errorhandler(404)690 def page_not_found(error):691 return render_template('page_not_found.html'), 404692693Note the ``404`` after the :func:`~flask.render_template` call. This694tells Flask that the status code of that page should be 404 which means695not found. By default 200 is assumed which translates to: all went well.

Extended quickstart docs for the headersArmin Ronacherbefore adoption5b16532

lines 696–713why, one step back
696
697.. _about-responses:698699About Responses700---------------701702The return value from a view function is automatically converted into a703response object for you. If the return value is a string it's converted704into a response object with the string as response body, an ``200 OK``705error code and a ``text/html`` mimetype. The logic that Flask applies to706converting return values into response objects is as follows:7077081. If a response object of the correct type is returned it's directly709 returned from the view.7102. If it's a string, a response object is created with that data and the711 default parameters.7123. If a tuple is returned the response object is created by passing the713 tuple as arguments to the response object's constructor.

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

lines 714–715why, one step back
7144. If none of that works, Flask will assume the return value is a
715 valid WSGI application and convert that into a response object.

Extended quickstart docs for the headersArmin Ronacherbefore adoption5b16532

lines 716–738why, one step back
716
717If you want to get hold of the resulting response object inside the view718you can use the :func:`~flask.make_response` function.719720Imagine you have a view like this:721722.. sourcecode:: python723724 @app.errorhandler(404)725 def not_found(error):726 return render_template('error.html'), 404727728You just need to wrap the return expression with729:func:`~flask.make_response` and get the result object to modify it, then730return it:731732.. sourcecode:: python733734 @app.errorhandler(404)735 def not_found(error):736 resp = make_response(render_template('error.html'), 404)737 resp.headers['X-Something'] = 'A value'738 return resp

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 739–744why, one step back
739
740.. _sessions:741742Sessions743--------744

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

lines 745–746why, one step back
745In addition to the request object there is also a second object called
746:class:`~flask.session` which allows you to store information specific to a

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 747–785why, one step back
747user from one request to the next. This is implemented on top of cookies
748for you and signs the cookies cryptographically. What this means is that749the user could look at the contents of your cookie but not modify it,750unless they know the secret key used for signing.751752In order to use sessions you have to set a secret key. Here is how753sessions work::754755 from flask import Flask, session, redirect, url_for, escape, request756757 app = Flask(__name__)758759 @app.route('/')760 def index():761 if 'username' in session:762 return 'Logged in as %s' % escape(session['username'])763 return 'You are not logged in'764765 @app.route('/login', methods=['GET', 'POST'])766 def login():767 if request.method == 'POST':768 session['username'] = request.form['username']769 return redirect(url_for('index'))770 return '''771 <form action="" method="post">772 <p><input type=text name=username>773 <p><input type=submit value=Login>774 </form>775 '''776777 @app.route('/logout')778 def logout():779 # remove the username from the session if its there780 session.pop('username', None)781 return redirect(url_for('index'))782783 # set the secret key. keep this really secret:784 app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'785

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

lines 786–787why, one step back
786The :func:`~flask.escape` mentioned here does escaping for you if you are
787not using the template engine (as in this example).

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 788–790why, one step back
788
789.. admonition:: How to generate good secret keys790

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

line 791why, one step back
791 The problem with random is that it's hard to judge what is truly random. And

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 792–808why, one step back
792 a secret key should be as random as possible. Your operating system
793 has ways to generate pretty random stuff based on a cryptographic794 random generator which can be used to get such a key:795796 >>> import os797 >>> os.urandom(24)798 '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'799800 Just take that thing and copy/paste it into your code and you're done.801802Message Flashing803----------------804805Good applications and user interfaces are all about feedback. If the user806does not get enough feedback they will probably end up hating the807application. Flask provides a really simple way to give feedback to a808user with the flashing system. The flashing system basically makes it

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

lines 809–811why, one step back
809possible to record a message at the end of a request and access it on the next
810(and only the next) request. This is usually combined with a layout811template to expose the message.

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 812–823why, one step back
812
813To flash a message use the :func:`~flask.flash` method, to get hold of the814messages you can use :func:`~flask.get_flashed_messages` which is also815available in the templates. Check out the :ref:`message-flashing-pattern`816for a full example.817818Logging819-------820821.. versionadded:: 0.3822823Sometimes you might be in a situation where you deal with data that

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

lines 824–827why, one step back
824should be correct, but actually is not. For example you may have some client-side
825code that sends an HTTP request to the server but it's obviously826malformed. This might be caused by a user tampering with the data, or the827client code failing. Most of the time it's okay to reply with ``400 Bad

Fixed another typoArmin Ronacherbefore adoptione2fed6c

lines 828–855why, one step back
828Request`` in that situation, but sometimes that won't do and the code has
829to continue working.830831You may still want to log that something fishy happened. This is where832loggers come in handy. As of Flask 0.3 a logger is preconfigured for you833to use.834835Here are some example log calls::836837 app.logger.debug('A value for debugging')838 app.logger.warning('A warning occurred (%d apples)', 42)839 app.logger.error('An error occurred')840841The attached :attr:`~flask.Flask.logger` is a standard logging842:class:`~logging.Logger`, so head over to the official `logging843documentation <http://docs.python.org/library/logging.html>`_ for more844information.845846Hooking in WSGI Middlewares847---------------------------848849If you want to add a WSGI middleware to your application you can wrap the850internal WSGI application. For example if you want to use one of the851middlewares from the Werkzeug package to work around bugs in lighttpd, you852can do it like this::853854 from werkzeug.contrib.fixers import LighttpdCGIRootFix855 app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)