Skip to content
Myr

quickstart.rst

This file

Path

docs/quickstart.rst

853 lines · 31.3 KiB

Last changed by

Merge pull request #486 from PaulMcMillan/docs_fixRon DuPlainbefore adoption1a19ddc

History of this file

Take it

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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

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

more editorial workOri Livnehbefore adoptiondf19ee9

lines 6–8why, one step back
6Eager to get started? This page gives a good introduction to Flask. It
7assumes you already have Flask installed. If you do not, head over to the8:ref:`installation` section.

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 9–25why, one step back
9
1011A 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()25

more editorial workOri Livnehbefore adoptiondf19ee9

lines 26–28why, one step back
26Just save it as `hello.py` (or something similar) and run it with your Python
27interpreter. Make sure to not call your application `flask.py` because this28would conflict with Flask itself.

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 29–34why, one step back
29
30::3132 $ python hello.py33 * Running on http://127.0.0.1:5000/34

more editorial workOri Livnehbefore adoptiondf19ee9

lines 35–36why, one step back
35Now head over to `http://127.0.0.1:5000/ <http://127.0.0.1:5000/>`_, and you
36should see your hello world greeting.

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 37–41why, one step back
37
38So 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

more editorial workOri Livnehbefore adoptiondf19ee9

lines 42–58why, one step back
42 the application's module. If you are using a single module (as in this
43 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.

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 59–65why, one step back
59
60To 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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

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.

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

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::

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 74–76why, one step back
74
75 app.run(host='0.0.0.0')76

more editorial workOri Livnehbefore adoptiondf19ee9

line 77why, one step back
77 This tells your operating system to listen on all public IPs.

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 78–79why, one step back
78
79

Move debugger details into a new section, #343.Ron DuPlainbefore adoption69e7a0a

lines 80–81why, one step back
80.. _debug-mode:
81

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 82–86why, one step back
82Debug Mode
83----------8485The :meth:`~flask.Flask.run` method is nice to start a local86development server, but you would have to restart it manually after each

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

lines 87–89why, one step back
87change to your code. That is not very nice and Flask can do better. If
88you enable debug support the server will reload itself on code changes,89and it will also provide you with a helpful debugger if things go wrong.

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 90–96why, one step back
90
91There are two ways to enable debugging. Either set that flag on the92application object::9394 app.debug = True95 app.run()96

more editorial workOri Livnehbefore adoptiondf19ee9

line 97why, one step back
97Or pass it as a parameter to run::

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 98–100why, one step back
98
99 app.run(debug=True)100

more editorial workOri Livnehbefore adoptiondf19ee9

line 101why, one step back
101Both methods have the exact same effect.

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 102–106why, one step back
102
103.. admonition:: Attention104105 Even though the interactive debugger does not work in forking environments106 (which makes it nearly impossible to use on production servers), it still

more editorial workOri Livnehbefore adoptiondf19ee9

lines 107–108why, one step back
107 allows the execution of arbitrary code. This makes it a major security risk
108 and therefore it **must never be used on production machines**.

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 109–116why, one step back
109
110Screenshot of the debugger in action:111112.. image:: _static/debugger.png113 :align: center114 :class: screenshot115 :alt: screenshot of debugger in action116

Move debugger details into a new section, #343.Ron DuPlainbefore adoption69e7a0a

line 117why, one step back
117Have another debugger in mind? See :ref:`working-with-debuggers`.

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 118–123why, one step back
118
119120Routing121-------122123Modern web applications have beautiful URLs. This helps people remember

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 125–128why, one step back
125mobile devices with slower network connections. If the user can directly
126go to the desired page without having to hit the index page it is more127likely they will like the page and come back next time.128

more editorial workOri Livnehbefore adoptiondf19ee9

lines 129–130why, one step back
129As you have seen above, the :meth:`~flask.Flask.route` decorator is used to
130bind a function to a URL. Here are some basic examples::

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 131–139why, one step back
131
132 @app.route('/')133 def index():134 return 'Index Page'135136 @app.route('/hello')137 def hello():138 return 'Hello World'139

more editorial workOri Livnehbefore adoptiondf19ee9

lines 140–141why, one step back
140But there is more to it! You can make certain parts of the URL dynamic and
141attach multiple rules to a function.

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 142–146why, one step back
142
143Variable Rules144``````````````145146To add variable parts to a URL you can mark these special sections as

more editorial workOri Livnehbefore adoptiondf19ee9

lines 147–149why, one step back
147``<variable_name>``. Such a part is then passed as keyword argument to your
148function. Optionally a converter can be specified by specifying a rule with149``<converter:variable_name>``. Here are some nice examples::

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 150–153why, one step back
150
151 @app.route('/user/<username>')152 def show_user_profile(username):153 # show the user profile for that user

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

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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

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

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

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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 160–170why, one step back
160
161The following converters exist:162163=========== ===========================================164`int` accepts integers165`float` like `int` but for floating point values166`path` like the default but also accepts slashes167=========== ===========================================168169.. admonition:: Unique URLs / Redirection Behaviour170

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

lines 171–172why, one step back
171 Flask's URL rules are based on Werkzeug's routing module. The idea
172 behind that module is to ensure beautiful and unique URLs based on

more editorial workOri Livnehbefore adoptiondf19ee9

line 173why, one step back
173 precedents laid down by Apache and earlier HTTP servers.

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 174–178why, one step back
174
175 Take these two rules::176177 @app.route('/projects/')178 def projects():

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

line 179why, one step back
179 return 'The project page'

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 180–182why, one step back
180
181 @app.route('/about')182 def about():

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

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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

line 184why, one step back
184

more editorial workOri Livnehbefore adoptiondf19ee9

lines 185–189why, one step back
185 Though they look rather similar, they differ in their use of the trailing
186 slash in the URL *definition*. In the first case, the canonical URL for the187 `projects` endpoint has a trailing slash. In that sense, it is similar to188 a folder on a file system. Accessing it without a trailing slash will cause189 Flask to redirect to the canonical URL with the trailing slash.

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

line 190why, one step back
190

more editorial workOri Livnehbefore adoptiondf19ee9

lines 191–193why, one step back
191 In the second case, however, the URL is defined without a trailing slash,
192 rather like the pathname of a file on UNIX-like systems. Accessing the URL193 with a trailing slash will produce a 404 "Not Found" error.

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

line 194why, one step back
194

more editorial workOri Livnehbefore adoptiondf19ee9

line 195why, one step back
195 This behavior allows relative URLs to continue working if users access the

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

line 196why, one step back
196 page when they forget a trailing slash, consistent with how Apache

more editorial workOri Livnehbefore adoptiondf19ee9

lines 197–198why, one step back
197 and other servers work. Also, the URLs will stay unique, which helps search
198 engines avoid indexing the same page twice.

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 199–205why, one step back
199
200201.. _url-building:202203URL Building204````````````205

more editorial workOri Livnehbefore adoptiondf19ee9

line 206why, one step back
206If it can match URLs, can Flask also generate them? Of course it can. To

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

line 207why, one step back
207build a URL to a specific function you can use the :func:`~flask.url_for`

more editorial workOri Livnehbefore adoptiondf19ee9

lines 208–211why, one step back
208function. It accepts the name of the function as first argument and a number
209of keyword arguments, each corresponding to the variable part of the URL rule.210Unknown variable parts are appended to the URL as query parameters. Here are211some examples:

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 212–234why, one step back
212
213>>> from flask import Flask, url_for214>>> app = Flask(__name__)215>>> @app.route('/')216... def index(): pass217...218>>> @app.route('/login')219... def login(): pass220...221>>> @app.route('/user/<username>')222... def profile(username): pass223...224>>> with app.test_request_context():225... print url_for('index')226... print url_for('login')227... print url_for('login', next='/')228... print url_for('profile', username='John Doe')229...230/231/login232/login?next=/233/user/John%20Doe234

more editorial workOri Livnehbefore adoptiondf19ee9

lines 235–236why, one step back
235(This also uses the :meth:`~flask.Flask.test_request_context` method, explained
236below. It tells Flask to behave as though it is handling a request, even

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

line 237why, one step back
237though we are interacting with it through a Python shell. Have a look at the

more editorial workOri Livnehbefore adoptiondf19ee9

line 238why, one step back
238explanation below. :ref:`context-locals`).

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

line 239why, one step back
239

more editorial workOri Livnehbefore adoptiondf19ee9

line 240why, one step back
240Why would you want to build URLs instead of hard-coding them into your

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 241–242why, one step back
241templates? There are three good reasons for this:
242

more editorial workOri Livnehbefore adoptiondf19ee9

lines 243–245why, one step back
2431. Reversing is often more descriptive than hard-coding the URLs. More
244 importantly, it allows you to change URLs in one go, without having to245 remember to change URLs all over the place.

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

line 246why, one step back
2462. URL building will handle escaping of special characters and Unicode

more editorial workOri Livnehbefore adoptiondf19ee9

lines 247–250why, one step back
247 data transparently for you, so you don't have to deal with them.
2483. If your application is placed outside the URL root (say, in249 ``/myapplication`` instead of ``/``), :func:`~flask.url_for` will handle250 that properly for you.

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 251–255why, one step back
251
252253HTTP Methods254````````````255

more editorial workOri Livnehbefore adoptiondf19ee9

lines 256–258why, one step back
256HTTP (the protocol web applications are speaking) knows different methods for
257accessing URLs. By default, a route only answers to `GET` requests, but that258can be changed by providing the `methods` argument to the

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 259–269why, one step back
259:meth:`~flask.Flask.route` decorator. Here are some examples::
260261 @app.route('/login', methods=['GET', 'POST'])262 def login():263 if request.method == 'POST':264 do_the_login()265 else:266 show_the_login_form()267268If `GET` is present, `HEAD` will be added automatically for you. You269don't have to deal with that. It will also make sure that `HEAD` requests

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

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

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 274–296why, one step back
274
275You have no idea what an HTTP method is? Worry not, here is a quick276introduction to HTTP methods and why they matter:277278The HTTP method (also often called "the verb") tells the server what the279clients wants to *do* with the requested page. The following methods are280very common:281282`GET`283 The browser tells the server to just *get* the information stored on284 that page and send it. This is probably the most common method.285286`HEAD`287 The browser tells the server to get the information, but it is only288 interested in the *headers*, not the content of the page. An289 application is supposed to handle that as if a `GET` request was290 received but to not deliver the actual content. In Flask you don't291 have to deal with that at all, the underlying Werkzeug library handles292 that for you.293294`POST`295 The browser tells the server that it wants to *post* some new296 information to that URL and that the server must ensure the data is

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 299–302why, one step back
299
300`PUT`301 Similar to `POST` but the server might trigger the store procedure302 multiple times by overwriting the old values more than once. Now you

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 305–329why, one step back
305 transmission: in this situation a system between the browser and the
306 server might receive the request safely a second time without breaking307 things. With `POST` that would not be possible because it must only308 be triggered once.309310`DELETE`311 Remove the information at the given location.312313`OPTIONS`314 Provides a quick way for a client to figure out which methods are315 supported by this URL. Starting with Flask 0.6, this is implemented316 for you automatically.317318Now the interesting part is that in HTML4 and XHTML1, the only methods a319form can submit to the server are `GET` and `POST`. But with JavaScript320and future HTML standards you can use the other methods as well. Furthermore321HTTP has become quite popular lately and browsers are no longer the only322clients that are using HTTP. For instance, many revision control system323use it.324325.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt326327Static Files328------------329

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

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

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

line 336why, one step back
336To generate URLs for static files, use the special ``'static'`` endpoint name::

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 337–350why, one step back
337
338 url_for('static', filename='style.css')339340The file has to be stored on the filesystem as ``static/style.css``.341342Rendering Templates343-------------------344345Generating HTML from within Python is not fun, and actually pretty346cumbersome because you have to do the HTML escaping on your own to keep347the application secure. Because of that Flask configures the `Jinja2348<http://jinja.pocoo.org/2/>`_ template engine for you automatically.349350To render a template you can use the :func:`~flask.render_template`

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 352–362why, one step back
352variables you want to pass to the template engine as keyword arguments.
353Here's a simple example of how to render a template::354355 from flask import render_template356357 @app.route('/hello/')358 @app.route('/hello/<name>')359 def hello(name=None):360 return render_template('hello.html', name=name)361362Flask will look for templates in the `templates` folder. So if your

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 364–403why, one step back
364package it's actually inside your package:
365366**Case 1**: a module::367368 /application.py369 /templates370 /hello.html371372**Case 2**: a package::373374 /application375 /__init__.py376 /templates377 /hello.html378379For templates you can use the full power of Jinja2 templates. Head over380to the the official `Jinja2 Template Documentation381<http://jinja.pocoo.org/2/documentation/templates>`_ for more information.382383Here is an example template:384385.. sourcecode:: html+jinja386387 <!doctype html>388 <title>Hello from Flask</title>389 {% if name %}390 <h1>Hello {{ name }}!</h1>391 {% else %}392 <h1>Hello World!</h1>393 {% endif %}394395Inside templates you also have access to the :class:`~flask.request`,396:class:`~flask.session` and :class:`~flask.g` [#]_ objects397as well as the :func:`~flask.get_flashed_messages` function.398399Templates are especially useful if inheritance is used. If you want to400know how that works, head over to the :ref:`template-inheritance` pattern401documentation. Basically template inheritance makes it possible to keep402certain elements on each page (like header, navigation and footer).403

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

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

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 407–440why, one step back
407markup to HTML) you can mark it as safe by using the
408:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the409template. Head over to the Jinja 2 documentation for more examples.410411Here is a basic introduction to how the :class:`~jinja2.Markup` class works:412413>>> from flask import Markup414>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'415Markup(u'<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')416>>> Markup.escape('<blink>hacker</blink>')417Markup(u'&lt;blink&gt;hacker&lt;/blink&gt;')418>>> Markup('<em>Marked up</em> &raquo; HTML').striptags()419u'Marked up \xbb HTML'420421.. versionchanged:: 0.5422423 Autoescaping is no longer enabled for all templates. The following424 extensions for templates trigger autoescaping: ``.html``, ``.htm``,425 ``.xml``, ``.xhtml``. Templates loaded from a string will have426 autoescaping disabled.427428.. [#] Unsure what that :class:`~flask.g` object is? It's something in which429 you can store information for your own needs, check the documentation of430 that object (:class:`~flask.g`) and the :ref:`sqlite3` for more431 information.432433434Accessing Request Data435----------------------436437For web applications it's crucial to react to the data a client sent to438the server. In Flask this information is provided by the global439:class:`~flask.request` object. If you have some experience with Python440you might be wondering how that object can be global and how Flask

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 442–458why, one step back
442
443444.. _context-locals:445446Context Locals447``````````````448449.. admonition:: Insider Information450451 If you want to understand how that works and how you can implement452 tests with context locals, read this section, otherwise just skip it.453454Certain objects in Flask are global objects, but not of the usual kind.455These objects are actually proxies to objects that are local to a specific456context. What a mouthful. But that is actually quite easy to understand.457458Imagine the context being the handling thread. A request comes in and the

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

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

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

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

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

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

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 473–614why, one step back
473context manager. In combination with the `with` statement it will bind a
474test request so that you can interact with it. Here is an example::475476 from flask import request477478 with app.test_request_context('/hello', method='POST'):479 # now you can do something with the request until the480 # end of the with block, such as basic assertions:481 assert request.path == '/hello'482 assert request.method == 'POST'483484The other possibility is passing a whole WSGI environment to the485:meth:`~flask.Flask.request_context` method::486487 from flask import request488489 with app.request_context(environ):490 assert request.method == 'POST'491492The Request Object493``````````````````494495The request object is documented in the API section and we will not cover496it here in detail (see :class:`~flask.request`). Here is a broad overview of497some of the most common operations. First of all you have to import it from498the `flask` module::499500 from flask import request501502The current request method is available by using the503:attr:`~flask.request.method` attribute. To access form data (data504transmitted in a `POST` or `PUT` request) you can use the505:attr:`~flask.request.form` attribute. Here is a full example of the two506attributes mentioned above::507508 @app.route('/login', methods=['POST', 'GET'])509 def login():510 error = None511 if request.method == 'POST':512 if valid_login(request.form['username'],513 request.form['password']):514 return log_the_user_in(request.form['username'])515 else:516 error = 'Invalid username/password'517 # this is executed if the request method was GET or the518 # credentials were invalid519520What happens if the key does not exist in the `form` attribute? In that521case a special :exc:`KeyError` is raised. You can catch it like a522standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request523error page is shown instead. So for many situations you don't have to524deal with that problem.525526To access parameters submitted in the URL (``?key=value``) you can use the527:attr:`~flask.request.args` attribute::528529 searchword = request.args.get('q', '')530531We recommend accessing URL parameters with `get` or by catching the532`KeyError` because users might change the URL and presenting them a 400533bad request page in that case is not user friendly.534535For a full list of methods and attributes of the request object, head over536to the :class:`~flask.request` documentation.537538539File Uploads540````````````541542You can handle uploaded files with Flask easily. Just make sure not to543forget to set the ``enctype="multipart/form-data"`` attribute on your HTML544form, otherwise the browser will not transmit your files at all.545546Uploaded files are stored in memory or at a temporary location on the547filesystem. You can access those files by looking at the548:attr:`~flask.request.files` attribute on the request object. Each549uploaded file is stored in that dictionary. It behaves just like a550standard Python :class:`file` object, but it also has a551:meth:`~werkzeug.datastructures.FileStorage.save` method that allows you to store that552file on the filesystem of the server. Here is a simple example showing how553that works::554555 from flask import request556557 @app.route('/upload', methods=['GET', 'POST'])558 def upload_file():559 if request.method == 'POST':560 f = request.files['the_file']561 f.save('/var/www/uploads/uploaded_file.txt')562 ...563564If you want to know how the file was named on the client before it was565uploaded to your application, you can access the566:attr:`~werkzeug.datastructures.FileStorage.filename` attribute. However please keep in567mind that this value can be forged so never ever trust that value. If you568want to use the filename of the client to store the file on the server,569pass it through the :func:`~werkzeug.utils.secure_filename` function that570Werkzeug provides for you::571572 from flask import request573 from werkzeug import secure_filename574575 @app.route('/upload', methods=['GET', 'POST'])576 def upload_file():577 if request.method == 'POST':578 f = request.files['the_file']579 f.save('/var/www/uploads/' + secure_filename(f.filename))580 ...581582For some better examples, checkout the :ref:`uploading-files` pattern.583584Cookies585```````586587To access cookies you can use the :attr:`~flask.Request.cookies`588attribute. To set cookies you can use the589:attr:`~flask.Response.set_cookie` method of response objects. The590:attr:`~flask.Request.cookies` attribute of request objects is a591dictionary with all the cookies the client transmits. If you want to use592sessions, do not use the cookies directly but instead use the593:ref:`sessions` in Flask that add some security on top of cookies for you.594595Reading cookies::596597 from flask import request598599 @app.route('/')600 def index():601 username = request.cookies.get('username')602 # use cookies.get(key) instead of cookies[key] to not get a603 # KeyError if the cookie is missing.604605Storing cookies::606607 from flask import make_response608609 @app.route('/')610 def index():611 resp = make_response(render_template(...))612 resp.set_cookie('username', 'the username')613 return resp614

Simple documentation corrections, mostly typos.Craig Dennisbefore adoption75050d4

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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

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

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

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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 624–676why, one step back
624For this also see :ref:`about-responses`.
625626Redirects and Errors627--------------------628629To redirect a user to somewhere else you can use the630:func:`~flask.redirect` function. To abort a request early with an error631code use the :func:`~flask.abort` function. Here an example how this works::632633 from flask import abort, redirect, url_for634635 @app.route('/')636 def index():637 return redirect(url_for('login'))638639 @app.route('/login')640 def login():641 abort(401)642 this_is_never_executed()643644This is a rather pointless example because a user will be redirected from645the index to a page they cannot access (401 means access denied) but it646shows how that works.647648By default a black and white error page is shown for each error code. If649you want to customize the error page, you can use the650:meth:`~flask.Flask.errorhandler` decorator::651652 from flask import render_template653654 @app.errorhandler(404)655 def page_not_found(error):656 return render_template('page_not_found.html'), 404657658Note the ``404`` after the :func:`~flask.render_template` call. This659tells Flask that the status code of that page should be 404 which means660not found. By default 200 is assumed which translates to: all went well.661662.. _about-responses:663664About Responses665---------------666667The return value from a view function is automatically converted into a668response object for you. If the return value is a string it's converted669into a response object with the string as response body, an ``200 OK``670error code and a ``text/html`` mimetype. The logic that Flask applies to671converting return values into response objects is as follows:6726731. If a response object of the correct type is returned it's directly674 returned from the view.6752. If it's a string, a response object is created with that data and the676 default parameters.

Changed the implementation of returning tuples from functionsArmin Ronacherbefore adoptioncf1641e

lines 677–681why, one step back
6773. If a tuple is returned the items in the tuple can provide extra
678 information. Such tuples have to be in the form ``(response, status,679 headers)`` where at least one item has to be in the tuple. The680 `status` value will override the status code and `headers` can be a681 list or dictionary of additional header values.

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 684–712why, one step back
684
685If you want to get hold of the resulting response object inside the view686you can use the :func:`~flask.make_response` function.687688Imagine you have a view like this:689690.. sourcecode:: python691692 @app.errorhandler(404)693 def not_found(error):694 return render_template('error.html'), 404695696You just need to wrap the return expression with697:func:`~flask.make_response` and get the result object to modify it, then698return it:699700.. sourcecode:: python701702 @app.errorhandler(404)703 def not_found(error):704 resp = make_response(render_template('error.html'), 404)705 resp.headers['X-Something'] = 'A value'706 return resp707708.. _sessions:709710Sessions711--------712

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 715–746why, one step back
715user from one request to the next. This is implemented on top of cookies
716for you and signs the cookies cryptographically. What this means is that717the user could look at the contents of your cookie but not modify it,718unless they know the secret key used for signing.719720In order to use sessions you have to set a secret key. Here is how721sessions work::722723 from flask import Flask, session, redirect, url_for, escape, request724725 app = Flask(__name__)726727 @app.route('/')728 def index():729 if 'username' in session:730 return 'Logged in as %s' % escape(session['username'])731 return 'You are not logged in'732733 @app.route('/login', methods=['GET', 'POST'])734 def login():735 if request.method == 'POST':736 session['username'] = request.form['username']737 return redirect(url_for('index'))738 return '''739 <form action="" method="post">740 <p><input type=text name=username>741 <p><input type=submit value=Login>742 </form>743 '''744745 @app.route('/logout')746 def logout():

Merge pull request #486 from PaulMcMillan/docs_fixRon DuPlainbefore adoption1a19ddc

line 747why, one step back
747 # remove the username from the session if it's there

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 748–753why, one step back
748 session.pop('username', None)
749 return redirect(url_for('index'))750751 # set the secret key. keep this really secret:752 app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'753

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 756–758why, one step back
756
757.. admonition:: How to generate good secret keys758

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 760–769why, one step back
760 a secret key should be as random as possible. Your operating system
761 has ways to generate pretty random stuff based on a cryptographic762 random generator which can be used to get such a key:763764 >>> import os765 >>> os.urandom(24)766 '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'767768 Just take that thing and copy/paste it into your code and you're done.769

Add cookie size limit note to sessions section.Ron DuPlainbefore adoptiondfd3ef6

lines 770–776why, one step back
770A note on cookie-based sessions: Flask will take the values you put into the
771session object and serialize them into a cookie. If you are finding some772values do not persist across requests, cookies are indeed enabled, and you are773not getting a clear error message, check the size of the cookie in your page774responses compared to the size supported by web browsers.775776

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 777–783why, one step back
777Message Flashing
778----------------779780Good applications and user interfaces are all about feedback. If the user781does not get enough feedback they will probably end up hating the782application. Flask provides a really simple way to give feedback to a783user with the flashing system. The flashing system basically makes it

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 787–798why, one step back
787
788To flash a message use the :func:`~flask.flash` method, to get hold of the789messages you can use :func:`~flask.get_flashed_messages` which is also790available in the templates. Check out the :ref:`message-flashing-pattern`791for a full example.792793Logging794-------795796.. versionadded:: 0.3797798Sometimes you might be in a situation where you deal with data that

Merge pull request #369 from FND/docsArmin Ronacherbefore adoptionf64098c

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

Leave eggs when finding the instance pathArmin Ronacherbefore adoptionfb1a673

lines 803–830why, one step back
803Request`` in that situation, but sometimes that won't do and the code has
804to continue working.805806You may still want to log that something fishy happened. This is where807loggers come in handy. As of Flask 0.3 a logger is preconfigured for you808to use.809810Here are some example log calls::811812 app.logger.debug('A value for debugging')813 app.logger.warning('A warning occurred (%d apples)', 42)814 app.logger.error('An error occurred')815816The attached :attr:`~flask.Flask.logger` is a standard logging817:class:`~logging.Logger`, so head over to the official `logging818documentation <http://docs.python.org/library/logging.html>`_ for more819information.820821Hooking in WSGI Middlewares822---------------------------823824If you want to add a WSGI middleware to your application you can wrap the825internal WSGI application. For example if you want to use one of the826middlewares from the Werkzeug package to work around bugs in lighttpd, you827can do it like this::828829 from werkzeug.contrib.fixers import LighttpdCGIRootFix830 app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

lines 831–853why, one step back
831
832.. _quickstart_deployment:833834Deploying to a Web Server835-------------------------836837Ready to deploy your new Flask app? To wrap up the quickstart, you can838immediately deploy to a hosted platform, all of which offer a free plan for839small projects:840841- `Deploying Flask on Heroku <http://devcenter.heroku.com/articles/python>`_842- `Deploying Flask on ep.io <https://www.ep.io/docs/quickstart/flask/>`_843- `Deploying WSGI on dotCloud <http://docs.dotcloud.com/services/python/>`_844 with `Flask-specific notes <http://flask.pocoo.org/snippets/48/>`_845846Other places where you can host your Flask app:847848- `Deploying Flask on Webfaction <http://flask.pocoo.org/snippets/65/>`_849- `Deploying Flask on Google App Engine <https://github.com/kamalgill/flask-appengine-template>`_850- `Sharing your Localhost Server with Localtunnel <http://flask.pocoo.org/snippets/89/>`_851852If you manage your own hosts and would like to host yourself, see the chapter853on :ref:`deployment`.