Skip to content
Myr

quickstart.rst

This file

Path

docs/quickstart.rst

850 lines · 30.4 KiB

Last changed by

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

History of this file

Take it

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

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 1–20why, one step back
1.. _quickstart:
23Quickstart4==========56Eager 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.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 #1318 from cerivera/masterMarkus Unterwaditzerbefore adoptione3ba459

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

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 22–28why, one step back
22
23So what did that code do?24251. First we imported the :class:`~flask.Flask` class. An instance of this26 class will be our WSGI application.272. Next we create an instance of this class. The first argument is the name of28 the application's module or package. If you are using a single module (as

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 29why, one step back
29 in this example), you should use ``__name__`` because depending on if it's

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 30–39why, one step back
30 started as application or imported as module the name will be different
31 (``'__main__'`` versus the actual import name). This is needed so that32 Flask knows where to look for templates, static files, and so on. For more33 information have a look at the :class:`~flask.Flask` documentation.343. We then use the :meth:`~flask.Flask.route` decorator to tell Flask what URL35 should trigger our function.364. The function is given a name which is also used to generate URLs for that37 particular function, and returns the message we want to display in the38 user's browser.39

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 40–42why, one step back
40Just save it as :file:`hello.py` or something similar. Make sure to not call
41your application :file:`flask.py` because this would conflict with Flask42itself.

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

line 43why, one step back
43

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

line 44why, one step back
44To run the application you can either use the :command:`flask` command or

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 45–47why, one step back
45python's ``-m`` switch with Flask. Before you can do that you need
46to tell your terminal the application to work with by exporting the47``FLASK_APP`` environment variable::

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

line 48why, one step back
48

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 49–50why, one step back
49 $ export FLASK_APP=hello.py
50 $ flask run

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

lines 51–52why, one step back
51 * Running on http://127.0.0.1:5000/
52

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 53–54why, one step back
53If you are on Windows, the environment variable syntax depends on command line
54interpreter. On Command Prompt::

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

line 55why, one step back
55

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 56–65why, one step back
56 C:\path\to\app>set FLASK_APP=hello.py
5758And on PowerShell::5960 PS C:\path\to\app> $env:FLASK_APP = "hello.py"6162Alternatively you can use :command:`python -m flask`::6364 $ export FLASK_APP=hello.py65 $ python -m flask run

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

lines 66–74why, one step back
66 * Running on http://127.0.0.1:5000/
6768This launches a very simple builtin server, which is good enough for testing69but probably not what you want to use in production. For deployment options see70:ref:`deployment`.7172Now head over to `http://127.0.0.1:5000/ <http://127.0.0.1:5000/>`_, and you73should see your hello world greeting.74

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 75–87why, one step back
75.. _public-server:
7677.. admonition:: Externally Visible Server7879 If you run the server you will notice that the server is only accessible80 from your own computer, not from any other in the network. This is the81 default because in debugging mode a user of the application can execute82 arbitrary Python code on your computer.8384 If you have the debugger disabled or trust the users on your network,85 you can make the server publicly available simply by adding86 ``--host=0.0.0.0`` to the command line::87

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 88why, one step back
88 flask run --host=0.0.0.0

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 89–91why, one step back
89
90 This tells your operating system to listen on all public IPs.91

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

line 92why, one step back
92

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 93–95why, one step back
93What to do if the Server does not Start
94---------------------------------------95

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 96why, one step back
96In case the :command:`python -m flask` fails or :command:`flask` does not exist,

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 97–102why, one step back
97there are multiple reasons this might be the case. First of all you need
98to look at the error message.99100Old Version of Flask101````````````````````102

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 103why, one step back
103Versions of Flask older than 0.11 use to have different ways to start the

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 104why, one step back
104application. In short, the :command:`flask` command did not exist, and

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 105why, one step back
105neither did :command:`python -m flask`. In that case you have two options:

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 106–111why, one step back
106either upgrade to newer Flask versions or have a look at the :ref:`server`
107docs to see the alternative method for running a server.108109Invalid Import Name110```````````````````111

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 112–115why, one step back
112The ``FLASK_APP`` environment variable is the name of the module to import at
113:command:`flask run`. In case that module is incorrectly named you will get an114import error upon start (or if debug is enabled when you navigate to the115application). It will tell you what it tried to import and why it failed.

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 116–124why, one step back
116
117The most common reason is a typo or because you did not actually create an118``app`` object.119120.. _debug-mode:121122Debug Mode123----------124

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 125–126why, one step back
125(Want to just log errors and stack traces? See :ref:`application-errors`)
126

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 127why, one step back
127The :command:`flask` script is nice to start a local development server, but

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 128–132why, one step back
128you would have to restart it manually after each change to your code.
129That is not very nice and Flask can do better. If you enable debug130support the server will reload itself on code changes, and it will also131provide you with a helpful debugger if things go wrong.132

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

lines 133–134why, one step back
133To enable all development features (including debug mode) you can export
134the ``FLASK_ENV`` environment variable and set it to ``development``

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 135why, one step back
135before running the server::

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

line 136why, one step back
136

Add Support for FLASK_ENV (#2570)Armin Ronacherbefore adoption2433522

line 137why, one step back
137 $ export FLASK_ENV=development

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 138why, one step back
138 $ flask run

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

line 139why, one step back
139

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

line 140why, one step back
140(On Windows you need to use ``set`` instead of ``export``.)

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 141why, one step back
141

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 142–146why, one step back
142This does the following things:
1431441. it activates the debugger1452. it activates the automatic reloader1463. it enables the debug mode on the Flask application.

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

lines 147–149why, one step back
147
148You can also control debug mode separately from the environment by149exporting ``FLASK_DEBUG=1``.

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 150–166why, one step back
150
151There are more parameters that are explained in the :ref:`server` docs.152153.. admonition:: Attention154155 Even though the interactive debugger does not work in forking environments156 (which makes it nearly impossible to use on production servers), it still157 allows the execution of arbitrary code. This makes it a major security risk158 and therefore it **must never be used on production machines**.159160Screenshot of the debugger in action:161162.. image:: _static/debugger.png163 :align: center164 :class: screenshot165 :alt: screenshot of debugger in action166

Merge pull request #2399 from davidism/docs-secret-keyDavid Lordbefore adoptiond13e41d

line 167why, one step back
167More information on using the debugger can be found in the `Werkzeug

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 168–171why, one step back
168documentation`_.
169170.. _Werkzeug documentation: http://werkzeug.pocoo.org/docs/debug/#using-the-debugger171

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 172–177why, one step back
172Have another debugger in mind? See :ref:`working-with-debuggers`.
173174175Routing176-------177

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 178–180why, one step back
178Modern web applications use meaningful URLs to help users. Users are more
179likely to like a page and come back if the page uses a meaningful URL they can180remember and use to directly visit a page.

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

line 181why, one step back
181

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 182why, one step back
182Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. ::

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 183–189why, one step back
183
184 @app.route('/')185 def index():186 return 'Index Page'187188 @app.route('/hello')189 def hello():

Merge pull request #1318 from cerivera/masterMarkus Unterwaditzerbefore adoptione3ba459

line 190why, one step back
190 return 'Hello, World'

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

line 191why, one step back
191

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 192–193why, one step back
192You can do more! You can make parts of the URL dynamic and attach multiple
193rules to a function.

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 194–197why, one step back
194
195Variable Rules196``````````````197

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 198–201why, one step back
198You can add variable sections to a URL by marking sections with
199``<variable_name>``. Your function then receives the ``<variable_name>``200as a keyword argument. Optionally, you can use a converter to specify the type201of the argument like ``<converter:variable_name>``. ::

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 202–212why, one step back
202
203 @app.route('/user/<username>')204 def show_user_profile(username):205 # show the user profile for that user206 return 'User %s' % username207208 @app.route('/post/<int:post_id>')209 def show_post(post_id):210 # show the post with the given id, the id is an integer211 return 'Post %d' % post_id212

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 213–216why, one step back
213 @app.route('/path/<path:subpath>')
214 def show_subpath(subpath):215 # show the subpath after /path/216 return 'Subpath %s' % subpath

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

line 217why, one step back
217

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 218why, one step back
218Converter types:

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

line 219why, one step back
219

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 220–226why, one step back
220========== ==========================================
221``string`` (default) accepts any text without a slash222``int`` accepts positive integers223``float`` accepts positive floating point values224``path`` like ``string`` but also accepts slashes225``uuid`` accepts UUID strings226========== ==========================================

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

line 227why, one step back
227

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 228–229why, one step back
228Unique URLs / Redirection Behavior
229``````````````````````````````````

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

line 230why, one step back
230

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 231why, one step back
231Take these two rules::

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

line 232why, one step back
232

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 233–235why, one step back
233 @app.route('/projects/')
234 def projects():235 return 'The project page'

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

line 236why, one step back
236

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 237–239why, one step back
237 @app.route('/about')
238 def about():239 return 'The about page'

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

line 240why, one step back
240

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 241–245why, one step back
241Though they look similar, they differ in their use of the trailing slash in
242the URL. In the first case, the canonical URL for the ``projects`` endpoint243uses a trailing slash. It's similar to a folder in a file system; if you244access the URL without a trailing slash, Flask redirects you to the245canonical URL with the trailing slash.

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

line 246why, one step back
246

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 247–249why, one step back
247In the second case, however, the URL definition lacks a trailing slash,
248like the pathname of a file on UNIX-like systems. Accessing the URL with a249trailing slash produces a 404 “Not Found” error.

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

line 250why, one step back
250

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 251–254why, one step back
251This behavior allows relative URLs to continue working even if the trailing
252slash is omitted, consistent with how Apache and other servers work. Also,253the URLs will stay unique, which helps search engines avoid indexing the254same page twice.

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 255–260why, one step back
255
256.. _url-building:257258URL Building259````````````260

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 261–264why, one step back
261To build a URL to a specific function, use the :func:`~flask.url_for` function.
262It accepts the name of the function as its first argument and any number of263keyword arguments, each corresponding to a variable part of the URL rule.264Unknown variable parts are appended to the URL as query parameters.

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 265–268why, one step back
265
266Why would you want to build URLs using the URL reversing function267:func:`~flask.url_for` instead of hard-coding them into your templates?268

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 269–276why, one step back
2691. Reversing is often more descriptive than hard-coding the URLs.
2702. You can change your URLs in one go instead of needing to remember to271 manually change hard-coded URLs.2723. URL building handles escaping of special characters and Unicode data273 transparently.2744. If your application is placed outside the URL root, for example, in275 ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly276 handles that for you.

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

line 277why, one step back
277

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 278–281why, one step back
278For example, here we use the :meth:`~flask.Flask.test_request_context` method
279to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context`280tells Flask to behave as though it's handling a request even while we use a281Python shell. See :ref:`context-locals`. ::

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

line 282why, one step back
282

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 283–309why, one step back
283 from flask import Flask, url_for
284285 app = Flask(__name__)286287 @app.route('/')288 def index():289 return 'index'290291 @app.route('/login')292 def login():293 return 'login'294295 @app.route('/user/<username>')296 def profile(username):297 return '{}'s profile'.format(username)298299 with app.test_request_context():300 print(url_for('index'))301 print(url_for('login'))302 print(url_for('login', next='/'))303 print(url_for('profile', username='John Doe'))304305 /306 /login307 /login?next=/308 /user/John%20Doe309

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 310–312why, one step back
310HTTP Methods
311````````````312

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 313–317why, one step back
313Web applications use different HTTP methods when accessing URLs. You should
314familiarize yourself with the HTTP methods as you work with Flask. By default,315a route only answers to ``GET`` requests. You can use the ``methods`` argument316of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods.317::

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 318–321why, one step back
318
319 @app.route('/login', methods=['GET', 'POST'])320 def login():321 if request.method == 'POST':

Fix code example for HTTP MethodsVladimir Krozbefore adoptiond08d96a

line 322why, one step back
322 return do_the_login()

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

line 323why, one step back
323 else:

Fix code example for HTTP MethodsVladimir Krozbefore adoptiond08d96a

line 324why, one step back
324 return show_the_login_form()

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

line 325why, one step back
325

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 326–328why, one step back
326If ``GET`` is present, Flask automatically adds support for the ``HEAD`` method
327and handles ``HEAD`` requests according to the the `HTTP RFC`_. Likewise,328``OPTIONS`` is automatically implemented for you.

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

line 329why, one step back
329

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 330why, one step back
330.. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 331–337why, one step back
331
332Static Files333------------334335Dynamic web applications also need static files. That's usually where336the CSS and JavaScript files are coming from. Ideally your web server is337configured to serve them for you, but during development Flask can do that

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

lines 338–339why, one step back
338as well. Just create a folder called :file:`static` in your package or next to
339your module and it will be available at ``/static`` on the application.

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 340–344why, one step back
340
341To generate URLs for static files, use the special ``'static'`` endpoint name::342343 url_for('static', filename='style.css')344

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 345why, one step back
345The file has to be stored on the filesystem as :file:`static/style.css`.

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 346–366why, one step back
346
347Rendering Templates348-------------------349350Generating HTML from within Python is not fun, and actually pretty351cumbersome because you have to do the HTML escaping on your own to keep352the application secure. Because of that Flask configures the `Jinja2353<http://jinja.pocoo.org/>`_ template engine for you automatically.354355To render a template you can use the :func:`~flask.render_template`356method. All you have to do is provide the name of the template and the357variables you want to pass to the template engine as keyword arguments.358Here's a simple example of how to render a template::359360 from flask import render_template361362 @app.route('/hello/')363 @app.route('/hello/<name>')364 def hello(name=None):365 return render_template('hello.html', name=name)366

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 367why, one step back
367Flask will look for templates in the :file:`templates` folder. So if your

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 368–396why, one step back
368application is a module, this folder is next to that module, if it's a
369package it's actually inside your package:370371**Case 1**: a module::372373 /application.py374 /templates375 /hello.html376377**Case 2**: a package::378379 /application380 /__init__.py381 /templates382 /hello.html383384For templates you can use the full power of Jinja2 templates. Head over385to the official `Jinja2 Template Documentation386<http://jinja.pocoo.org/docs/templates>`_ for more information.387388Here is an example template:389390.. sourcecode:: html+jinja391392 <!doctype html>393 <title>Hello from Flask</title>394 {% if name %}395 <h1>Hello {{ name }}!</h1>396 {% else %}

Merge pull request #1318 from cerivera/masterMarkus Unterwaditzerbefore adoptione3ba459

line 397why, one step back
397 <h1>Hello, World!</h1>

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 398–408why, one step back
398 {% endif %}
399400Inside templates you also have access to the :class:`~flask.request`,401:class:`~flask.session` and :class:`~flask.g` [#]_ objects402as well as the :func:`~flask.get_flashed_messages` function.403404Templates are especially useful if inheritance is used. If you want to405know how that works, head over to the :ref:`template-inheritance` pattern406documentation. Basically template inheritance makes it possible to keep407certain elements on each page (like header, navigation and footer).408

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 410–415why, one step back
410automatically. If you can trust a variable and you know that it will be
411safe HTML (for example because it came from a module that converts wiki412markup to HTML) you can mark it as safe by using the413:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the414template. Head over to the Jinja 2 documentation for more examples.415

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 416why, one step back
416Here is a basic introduction to how the :class:`~jinja2.Markup` class works::

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

line 417why, one step back
417

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 418–424why, one step back
418 >>> from flask import Markup
419 >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'420 Markup(u'<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')421 >>> Markup.escape('<blink>hacker</blink>')422 Markup(u'&lt;blink&gt;hacker&lt;/blink&gt;')423 >>> Markup('<em>Marked up</em> &raquo; HTML').striptags()424 u'Marked up \xbb HTML'

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 425–441why, one step back
425
426.. versionchanged:: 0.5427428 Autoescaping is no longer enabled for all templates. The following429 extensions for templates trigger autoescaping: ``.html``, ``.htm``,430 ``.xml``, ``.xhtml``. Templates loaded from a string will have431 autoescaping disabled.432433.. [#] Unsure what that :class:`~flask.g` object is? It's something in which434 you can store information for your own needs, check the documentation of435 that object (:class:`~flask.g`) and the :ref:`sqlite3` for more436 information.437438439Accessing Request Data440----------------------441

Merge pull request #1299 from sateeshkumarb/patch-1Markus Unterwaditzerbefore adoption4fde65e

line 442why, one step back
442For web applications it's crucial to react to the data a client sends to

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 443–477why, one step back
443the server. In Flask this information is provided by the global
444:class:`~flask.request` object. If you have some experience with Python445you might be wondering how that object can be global and how Flask446manages to still be threadsafe. The answer is context locals:447448449.. _context-locals:450451Context Locals452``````````````453454.. admonition:: Insider Information455456 If you want to understand how that works and how you can implement457 tests with context locals, read this section, otherwise just skip it.458459Certain objects in Flask are global objects, but not of the usual kind.460These objects are actually proxies to objects that are local to a specific461context. What a mouthful. But that is actually quite easy to understand.462463Imagine the context being the handling thread. A request comes in and the464web server decides to spawn a new thread (or something else, the465underlying object is capable of dealing with concurrency systems other466than threads). When Flask starts its internal request handling it467figures out that the current thread is the active context and binds the468current application and the WSGI environments to that context (thread).469It does that in an intelligent way so that one application can invoke another470application without breaking.471472So what does this mean to you? Basically you can completely ignore that473this is the case unless you are doing something like unit testing. You474will notice that code which depends on a request object will suddenly break475because there is no request object. The solution is creating a request476object yourself and binding it to the context. The easiest solution for477unit testing is to use the :meth:`~flask.Flask.test_request_context`

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 478why, one step back
478context manager. In combination with the ``with`` statement it will bind a

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 479–500why, one step back
479test request so that you can interact with it. Here is an example::
480481 from flask import request482483 with app.test_request_context('/hello', method='POST'):484 # now you can do something with the request until the485 # end of the with block, such as basic assertions:486 assert request.path == '/hello'487 assert request.method == 'POST'488489The other possibility is passing a whole WSGI environment to the490:meth:`~flask.Flask.request_context` method::491492 from flask import request493494 with app.request_context(environ):495 assert request.method == 'POST'496497The Request Object498``````````````````499500The request object is documented in the API section and we will not cover

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 501why, one step back
501it here in detail (see :class:`~flask.Request`). Here is a broad overview of

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

line 502why, one step back
502some of the most common operations. First of all you have to import it from

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 503why, one step back
503the ``flask`` module::

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 504–507why, one step back
504
505 from flask import request506507The current request method is available by using the

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 508why, one step back
508:attr:`~flask.Request.method` attribute. To access form data (data

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 509why, one step back
509transmitted in a ``POST`` or ``PUT`` request) you can use the

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 510why, one step back
510:attr:`~flask.Request.form` attribute. Here is a full example of the two

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 511–525why, one step back
511attributes mentioned above::
512513 @app.route('/login', methods=['POST', 'GET'])514 def login():515 error = None516 if request.method == 'POST':517 if valid_login(request.form['username'],518 request.form['password']):519 return log_the_user_in(request.form['username'])520 else:521 error = 'Invalid username/password'522 # the code below is executed if the request method523 # was GET or the credentials were invalid524 return render_template('login.html', error=error)525

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 526why, one step back
526What happens if the key does not exist in the ``form`` attribute? In that

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 527–532why, one step back
527case a special :exc:`KeyError` is raised. You can catch it like a
528standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request529error page is shown instead. So for many situations you don't have to530deal with that problem.531532To access parameters submitted in the URL (``?key=value``) you can use the

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 533why, one step back
533:attr:`~flask.Request.args` attribute::

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 534–537why, one step back
534
535 searchword = request.args.get('key', '')536537We recommend accessing URL parameters with `get` or by catching the

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 538why, one step back
538:exc:`KeyError` because users might change the URL and presenting them a 400

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 539–541why, one step back
539bad request page in that case is not user friendly.
540541For a full list of methods and attributes of the request object, head over

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 542why, one step back
542to the :class:`~flask.Request` documentation.

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 543–578why, one step back
543
544545File Uploads546````````````547548You can handle uploaded files with Flask easily. Just make sure not to549forget to set the ``enctype="multipart/form-data"`` attribute on your HTML550form, otherwise the browser will not transmit your files at all.551552Uploaded files are stored in memory or at a temporary location on the553filesystem. You can access those files by looking at the554:attr:`~flask.request.files` attribute on the request object. Each555uploaded file is stored in that dictionary. It behaves just like a556standard Python :class:`file` object, but it also has a557:meth:`~werkzeug.datastructures.FileStorage.save` method that allows you to store that558file on the filesystem of the server. Here is a simple example showing how559that works::560561 from flask import request562563 @app.route('/upload', methods=['GET', 'POST'])564 def upload_file():565 if request.method == 'POST':566 f = request.files['the_file']567 f.save('/var/www/uploads/uploaded_file.txt')568 ...569570If you want to know how the file was named on the client before it was571uploaded to your application, you can access the572:attr:`~werkzeug.datastructures.FileStorage.filename` attribute. However please keep in573mind that this value can be forged so never ever trust that value. If you574want to use the filename of the client to store the file on the server,575pass it through the :func:`~werkzeug.utils.secure_filename` function that576Werkzeug provides for you::577578 from flask import request

Merge pull request #1461 from justinwp/patch-1Markus Unterwaditzerbefore adoption1e15e17

line 579why, one step back
579 from werkzeug.utils import secure_filename

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 580–667why, one step back
580
581 @app.route('/upload', methods=['GET', 'POST'])582 def upload_file():583 if request.method == 'POST':584 f = request.files['the_file']585 f.save('/var/www/uploads/' + secure_filename(f.filename))586 ...587588For some better examples, checkout the :ref:`uploading-files` pattern.589590Cookies591```````592593To access cookies you can use the :attr:`~flask.Request.cookies`594attribute. To set cookies you can use the595:attr:`~flask.Response.set_cookie` method of response objects. The596:attr:`~flask.Request.cookies` attribute of request objects is a597dictionary with all the cookies the client transmits. If you want to use598sessions, do not use the cookies directly but instead use the599:ref:`sessions` in Flask that add some security on top of cookies for you.600601Reading cookies::602603 from flask import request604605 @app.route('/')606 def index():607 username = request.cookies.get('username')608 # use cookies.get(key) instead of cookies[key] to not get a609 # KeyError if the cookie is missing.610611Storing cookies::612613 from flask import make_response614615 @app.route('/')616 def index():617 resp = make_response(render_template(...))618 resp.set_cookie('username', 'the username')619 return resp620621Note that cookies are set on response objects. Since you normally622just return strings from the view functions Flask will convert them into623response objects for you. If you explicitly want to do that you can use624the :meth:`~flask.make_response` function and then modify it.625626Sometimes you might want to set a cookie at a point where the response627object does not exist yet. This is possible by utilizing the628:ref:`deferred-callbacks` pattern.629630For this also see :ref:`about-responses`.631632Redirects and Errors633--------------------634635To redirect a user to another endpoint, use the :func:`~flask.redirect`636function; to abort a request early with an error code, use the637:func:`~flask.abort` function::638639 from flask import abort, redirect, url_for640641 @app.route('/')642 def index():643 return redirect(url_for('login'))644645 @app.route('/login')646 def login():647 abort(401)648 this_is_never_executed()649650This is a rather pointless example because a user will be redirected from651the index to a page they cannot access (401 means access denied) but it652shows how that works.653654By default a black and white error page is shown for each error code. If655you want to customize the error page, you can use the656:meth:`~flask.Flask.errorhandler` decorator::657658 from flask import render_template659660 @app.errorhandler(404)661 def page_not_found(error):662 return render_template('page_not_found.html'), 404663664Note the ``404`` after the :func:`~flask.render_template` call. This665tells Flask that the status code of that page should be 404 which means666not found. By default 200 is assumed which translates to: all went well.667

Merge pull request #1429 from flying-sheep/errorhandler-rework-docsMarkus Unterwaditzerbefore adoption06f2be3

lines 668–669why, one step back
668See :ref:`error-handlers` for more details.
669

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 670–677why, one step back
670.. _about-responses:
671672About Responses673---------------674675The return value from a view function is automatically converted into a676response object for you. If the return value is a string it's converted677into a response object with the string as response body, a ``200 OK``

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 678why, one step back
678status code and a :mimetype:`text/html` mimetype. The logic that Flask applies to

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 679–687why, one step back
679converting return values into response objects is as follows:
6806811. If a response object of the correct type is returned it's directly682 returned from the view.6832. If it's a string, a response object is created with that data and the684 default parameters.6853. If a tuple is returned the items in the tuple can provide extra686 information. Such tuples have to be in the form ``(response, status,687 headers)`` or ``(response, headers)`` where at least one item has

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 688–689why, one step back
688 to be in the tuple. The ``status`` value will override the status code
689 and ``headers`` can be a list or dictionary of additional header values.

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 690–695why, one step back
6904. If none of that works, Flask will assume the return value is a
691 valid WSGI application and convert that into a response object.692693If you want to get hold of the resulting response object inside the view694you can use the :func:`~flask.make_response` function.695

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 696why, one step back
696Imagine you have a view like this::

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 697–703why, one step back
697
698 @app.errorhandler(404)699 def not_found(error):700 return render_template('error.html'), 404701702You just need to wrap the return expression with703:func:`~flask.make_response` and get the response object to modify it, then

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 704why, one step back
704return it::

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 705–730why, one step back
705
706 @app.errorhandler(404)707 def not_found(error):708 resp = make_response(render_template('error.html'), 404)709 resp.headers['X-Something'] = 'A value'710 return resp711712.. _sessions:713714Sessions715--------716717In addition to the request object there is also a second object called718:class:`~flask.session` which allows you to store information specific to a719user from one request to the next. This is implemented on top of cookies720for you and signs the cookies cryptographically. What this means is that721the user could look at the contents of your cookie but not modify it,722unless they know the secret key used for signing.723724In order to use sessions you have to set a secret key. Here is how725sessions work::726727 from flask import Flask, session, redirect, url_for, escape, request728729 app = Flask(__name__)730

Merge pull request #2399 from davidism/docs-secret-keyDavid Lordbefore adoptiond13e41d

lines 731–733why, one step back
731 # Set the secret key to some random bytes. Keep this really secret!
732 app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'733

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 734–745why, one step back
734 @app.route('/')
735 def index():736 if 'username' in session:737 return 'Logged in as %s' % escape(session['username'])738 return 'You are not logged in'739740 @app.route('/login', methods=['GET', 'POST'])741 def login():742 if request.method == 'POST':743 session['username'] = request.form['username']744 return redirect(url_for('index'))745 return '''

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 746why, one step back
746 <form method="post">

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 747–762why, one step back
747 <p><input type=text name=username>
748 <p><input type=submit value=Login>749 </form>750 '''751752 @app.route('/logout')753 def logout():754 # remove the username from the session if it's there755 session.pop('username', None)756 return redirect(url_for('index'))757758The :func:`~flask.escape` mentioned here does escaping for you if you are759not using the template engine (as in this example).760761.. admonition:: How to generate good secret keys762

Merge pull request #2399 from davidism/docs-secret-keyDavid Lordbefore adoptiond13e41d

lines 763–766why, one step back
763 A secret key should be as random as possible. Your operating system has
764 ways to generate pretty random data based on a cryptographic random765 generator. Use the following command to quickly generate a value for766 :attr:`Flask.secret_key` (or :data:`SECRET_KEY`)::

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

line 767why, one step back
767

Merge pull request #2399 from davidism/docs-secret-keyDavid Lordbefore adoptiond13e41d

lines 768–769why, one step back
768 $ python -c 'import os; print(os.urandom(16))'
769 b'_5#y2L"F4Q8z\n\xec]/'

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

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

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 777–779why, one step back
777Besides the default client-side based sessions, if you want to handle
778sessions on the server-side instead, there are several779Flask extensions that support this.

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 780–824why, one step back
780
781Message Flashing782----------------783784Good applications and user interfaces are all about feedback. If the user785does not get enough feedback they will probably end up hating the786application. Flask provides a really simple way to give feedback to a787user with the flashing system. The flashing system basically makes it788possible to record a message at the end of a request and access it on the next789(and only the next) request. This is usually combined with a layout790template to expose the message.791792To flash a message use the :func:`~flask.flash` method, to get hold of the793messages you can use :func:`~flask.get_flashed_messages` which is also794available in the templates. Check out the :ref:`message-flashing-pattern`795for a full example.796797Logging798-------799800.. versionadded:: 0.3801802Sometimes you might be in a situation where you deal with data that803should be correct, but actually is not. For example you may have some client-side804code that sends an HTTP request to the server but it's obviously805malformed. This might be caused by a user tampering with the data, or the806client code failing. Most of the time it's okay to reply with ``400 Bad807Request`` in that situation, but sometimes that won't do and the code has808to continue working.809810You may still want to log that something fishy happened. This is where811loggers come in handy. As of Flask 0.3 a logger is preconfigured for you812to use.813814Here are some example log calls::815816 app.logger.debug('A value for debugging')817 app.logger.warning('A warning occurred (%d apples)', 42)818 app.logger.error('An error occurred')819820The attached :attr:`~flask.Flask.logger` is a standard logging821:class:`~logging.Logger`, so head over to the official `logging822documentation <https://docs.python.org/library/logging.html>`_ for more823information.824

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

lines 825–826why, one step back
825Read more on :ref:`application-errors`.
826

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 827–837why, one step back
827Hooking in WSGI Middlewares
828---------------------------829830If you want to add a WSGI middleware to your application you can wrap the831internal WSGI application. For example if you want to use one of the832middlewares from the Werkzeug package to work around bugs in lighttpd, you833can do it like this::834835 from werkzeug.contrib.fixers import LighttpdCGIRootFix836 app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)837

Merge pull request #1376 from KWinston/masterMarkus Unterwaditzerbefore adoptionec5811d

lines 838–846why, one step back
838Using Flask Extensions
839----------------------840841Extensions are packages that help you accomplish common tasks. For842example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple843and easy to use with Flask.844845For more on Flask extensions, have a look at :ref:`extensions`.846

Merge pull request #1213 from defuz/config-patchMarkus Unterwaditzerbefore adoptionfe2d75e

lines 847–849why, one step back
847Deploying to a Web Server
848-------------------------849

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

line 850why, one step back
850Ready to deploy your new Flask app? Go to :ref:`deployment`.