Skip to content
Myr

quickstart.rst

This file

Path

docs/quickstart.rst

851 lines · 30.3 KiB

Last changed by

Merge pull request #2916 from tombusby/patch-1Grey Libefore adoption393bd46

History of this file

Take it

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

lines 1–28why, 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():21 return 'Hello, World!'2223So 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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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.

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

lines 43–44why, one step back
43
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::

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

lines 66–87why, 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.7475.. _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

Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

lines 89–95why, one step back
89
90 This tells your operating system to listen on all public IPs.919293What to do if the Server does not Start94---------------------------------------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,

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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:

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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.

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

lines 127–132why, one step back
127The :command:`flask` script is nice to start a local development server, but
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::

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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``.

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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.

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

lines 183–191why, one step back
183
184 @app.route('/')185 def index():186 return 'Index Page'187188 @app.route('/hello')189 def hello():190 return 'Hello, World'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.

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

line 217why, one step back
217

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 218why, one step back
218Converter types:

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

line 227why, one step back
227

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

line 230why, one step back
230

Merge pull request #2637 from pallets/quickstart-unique-urlsDavid Lordbefore adoptionb0c1da1

line 231why, one step back
231The following two rules differ in their use of a trailing slash. ::

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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'

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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'

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

line 240why, one step back
240

Merge pull request #2637 from pallets/quickstart-unique-urlsDavid Lordbefore adoptionb0c1da1

lines 241–244why, one step back
241The canonical URL for the ``projects`` endpoint has a trailing slash.
242It's similar to a folder in a file system. If you access the URL without243a trailing slash, Flask redirects you to the canonical URL with the244trailing slash.

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

line 245why, one step back
245

Merge pull request #2637 from pallets/quickstart-unique-urlsDavid Lordbefore adoptionb0c1da1

lines 246–250why, one step back
246The canonical URL for the ``about`` endpoint does not have a trailing
247slash. It's similar to the pathname of a file. Accessing the URL with a248trailing slash produces a 404 "Not Found" error. This helps keep URLs249unique for these resources, which helps search engines avoid indexing250the same page twice.

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

lines 251–257why, one step back
251
252253.. _url-building:254255URL Building256````````````257

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 266–270why, one step back
2661. Reversing is often more descriptive than hard-coding the URLs.
2672. You can change your URLs in one go instead of needing to remember to268 manually change hard-coded URLs.2693. URL building handles escaping of special characters and Unicode data270 transparently.

Merge pull request #2637 from pallets/quickstart-unique-urlsDavid Lordbefore adoptionb0c1da1

lines 271–273why, one step back
2714. The generated paths are always absolute, avoiding unexpected behavior
272 of relative paths in browsers.2735. If your application is placed outside the URL root, for example, in

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 274–275why, one step back
274 ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly
275 handles that for you.

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

line 276why, one step back
276

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

line 281why, one step back
281

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 282–295why, one step back
282 from flask import Flask, url_for
283284 app = Flask(__name__)285286 @app.route('/')287 def index():288 return 'index'289290 @app.route('/login')291 def login():292 return 'login'293294 @app.route('/user/<username>')295 def profile(username):

Merge branch '1.0-maintenance'David Lordbefore adoption1fa9185

line 296why, one step back
296 return '{}\'s profile'.format(username)

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 297–303why, one step back
297
298 with app.test_request_context():299 print(url_for('index'))300 print(url_for('login'))301 print(url_for('login', next='/'))302 print(url_for('profile', username='John Doe'))303

Merge pull request #2916 from tombusby/patch-1Grey Libefore adoption393bd46

lines 304–307why, one step back
304 # /
305 # /login306 # /login?next=/307 # /user/John%20Doe

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 308why, one step back
308

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

line 317why, one step back
317

Merge branch '1.0-maintenance'David Lordbefore adoption1fa9185

lines 318–319why, one step back
318 from flask import request
319

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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

Fix code example for HTTP MethodsVladimir Krozbefore adoptiond08d96a

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

line 324why, one step back
324 else:

Fix code example for HTTP MethodsVladimir Krozbefore adoptiond08d96a

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

line 326why, one step back
326

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 327why, one step back
327If ``GET`` is present, Flask automatically adds support for the ``HEAD`` method

Merge branch '1.0-maintenance'David Lordbefore adoption1fa9185

line 328why, one step back
328and handles ``HEAD`` requests according to the `HTTP RFC`_. Likewise,

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 329why, one step back
329``OPTIONS`` is automatically implemented for you.

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

line 330why, one step back
330

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

lines 332–409why, one step back
332
333Static Files334------------335336Dynamic web applications also need static files. That's usually where337the CSS and JavaScript files are coming from. Ideally your web server is338configured to serve them for you, but during development Flask can do that339as well. Just create a folder called :file:`static` in your package or next to340your module and it will be available at ``/static`` on the application.341342To generate URLs for static files, use the special ``'static'`` endpoint name::343344 url_for('static', filename='style.css')345346The file has to be stored on the filesystem as :file:`static/style.css`.347348Rendering Templates349-------------------350351Generating HTML from within Python is not fun, and actually pretty352cumbersome because you have to do the HTML escaping on your own to keep353the application secure. Because of that Flask configures the `Jinja2354<http://jinja.pocoo.org/>`_ template engine for you automatically.355356To render a template you can use the :func:`~flask.render_template`357method. All you have to do is provide the name of the template and the358variables you want to pass to the template engine as keyword arguments.359Here's a simple example of how to render a template::360361 from flask import render_template362363 @app.route('/hello/')364 @app.route('/hello/<name>')365 def hello(name=None):366 return render_template('hello.html', name=name)367368Flask will look for templates in the :file:`templates` folder. So if your369application is a module, this folder is next to that module, if it's a370package it's actually inside your package:371372**Case 1**: a module::373374 /application.py375 /templates376 /hello.html377378**Case 2**: a package::379380 /application381 /__init__.py382 /templates383 /hello.html384385For templates you can use the full power of Jinja2 templates. Head over386to the official `Jinja2 Template Documentation387<http://jinja.pocoo.org/docs/templates>`_ for more information.388389Here is an example template:390391.. sourcecode:: html+jinja392393 <!doctype html>394 <title>Hello from Flask</title>395 {% if name %}396 <h1>Hello {{ name }}!</h1>397 {% else %}398 <h1>Hello, World!</h1>399 {% endif %}400401Inside templates you also have access to the :class:`~flask.request`,402:class:`~flask.session` and :class:`~flask.g` [#]_ objects403as well as the :func:`~flask.get_flashed_messages` function.404405Templates are especially useful if inheritance is used. If you want to406know how that works, head over to the :ref:`template-inheritance` pattern407documentation. Basically template inheritance makes it possible to keep408certain elements on each page (like header, navigation and footer).409

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

line 418why, one step back
418

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

lines 426–501why, one step back
426
427.. versionchanged:: 0.5428429 Autoescaping is no longer enabled for all templates. The following430 extensions for templates trigger autoescaping: ``.html``, ``.htm``,431 ``.xml``, ``.xhtml``. Templates loaded from a string will have432 autoescaping disabled.433434.. [#] Unsure what that :class:`~flask.g` object is? It's something in which435 you can store information for your own needs, check the documentation of436 that object (:class:`~flask.g`) and the :ref:`sqlite3` for more437 information.438439440Accessing Request Data441----------------------442443For web applications it's crucial to react to the data a client sends to444the server. In Flask this information is provided by the global445:class:`~flask.request` object. If you have some experience with Python446you might be wondering how that object can be global and how Flask447manages to still be threadsafe. The answer is context locals:448449450.. _context-locals:451452Context Locals453``````````````454455.. admonition:: Insider Information456457 If you want to understand how that works and how you can implement458 tests with context locals, read this section, otherwise just skip it.459460Certain objects in Flask are global objects, but not of the usual kind.461These objects are actually proxies to objects that are local to a specific462context. What a mouthful. But that is actually quite easy to understand.463464Imagine the context being the handling thread. A request comes in and the465web server decides to spawn a new thread (or something else, the466underlying object is capable of dealing with concurrency systems other467than threads). When Flask starts its internal request handling it468figures out that the current thread is the active context and binds the469current application and the WSGI environments to that context (thread).470It does that in an intelligent way so that one application can invoke another471application without breaking.472473So what does this mean to you? Basically you can completely ignore that474this is the case unless you are doing something like unit testing. You475will notice that code which depends on a request object will suddenly break476because there is no request object. The solution is creating a request477object yourself and binding it to the context. The easiest solution for478unit testing is to use the :meth:`~flask.Flask.test_request_context`479context manager. In combination with the ``with`` statement it will bind a480test request so that you can interact with it. Here is an example::481482 from flask import request483484 with app.test_request_context('/hello', method='POST'):485 # now you can do something with the request until the486 # end of the with block, such as basic assertions:487 assert request.path == '/hello'488 assert request.method == 'POST'489490The other possibility is passing a whole WSGI environment to the491:meth:`~flask.Flask.request_context` method::492493 from flask import request494495 with app.request_context(environ):496 assert request.method == 'POST'497498The Request Object499``````````````````500501The request object is documented in the API section and we will not cover

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

lines 505–508why, one step back
505
506 from flask import request507508The current request method is available by using the

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

lines 512–526why, one step back
512attributes mentioned above::
513514 @app.route('/login', methods=['POST', 'GET'])515 def login():516 error = None517 if request.method == 'POST':518 if valid_login(request.form['username'],519 request.form['password']):520 return log_the_user_in(request.form['username'])521 else:522 error = 'Invalid username/password'523 # the code below is executed if the request method524 # was GET or the credentials were invalid525 return render_template('login.html', error=error)526

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

lines 535–542why, one step back
535
536 searchword = request.args.get('key', '')537538We recommend accessing URL parameters with `get` or by catching the539:exc:`KeyError` because users might change the URL and presenting them a 400540bad request page in that case is not user friendly.541542For a full list of methods and attributes of the request object, head over

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

lines 544–688why, one step back
544
545546File Uploads547````````````548549You can handle uploaded files with Flask easily. Just make sure not to550forget to set the ``enctype="multipart/form-data"`` attribute on your HTML551form, otherwise the browser will not transmit your files at all.552553Uploaded files are stored in memory or at a temporary location on the554filesystem. You can access those files by looking at the555:attr:`~flask.request.files` attribute on the request object. Each556uploaded file is stored in that dictionary. It behaves just like a557standard Python :class:`file` object, but it also has a558:meth:`~werkzeug.datastructures.FileStorage.save` method that allows you to store that559file on the filesystem of the server. Here is a simple example showing how560that works::561562 from flask import request563564 @app.route('/upload', methods=['GET', 'POST'])565 def upload_file():566 if request.method == 'POST':567 f = request.files['the_file']568 f.save('/var/www/uploads/uploaded_file.txt')569 ...570571If you want to know how the file was named on the client before it was572uploaded to your application, you can access the573:attr:`~werkzeug.datastructures.FileStorage.filename` attribute. However please keep in574mind that this value can be forged so never ever trust that value. If you575want to use the filename of the client to store the file on the server,576pass it through the :func:`~werkzeug.utils.secure_filename` function that577Werkzeug provides for you::578579 from flask import request580 from werkzeug.utils import secure_filename581582 @app.route('/upload', methods=['GET', 'POST'])583 def upload_file():584 if request.method == 'POST':585 f = request.files['the_file']586 f.save('/var/www/uploads/' + secure_filename(f.filename))587 ...588589For some better examples, checkout the :ref:`uploading-files` pattern.590591Cookies592```````593594To access cookies you can use the :attr:`~flask.Request.cookies`595attribute. To set cookies you can use the596:attr:`~flask.Response.set_cookie` method of response objects. The597:attr:`~flask.Request.cookies` attribute of request objects is a598dictionary with all the cookies the client transmits. If you want to use599sessions, do not use the cookies directly but instead use the600:ref:`sessions` in Flask that add some security on top of cookies for you.601602Reading cookies::603604 from flask import request605606 @app.route('/')607 def index():608 username = request.cookies.get('username')609 # use cookies.get(key) instead of cookies[key] to not get a610 # KeyError if the cookie is missing.611612Storing cookies::613614 from flask import make_response615616 @app.route('/')617 def index():618 resp = make_response(render_template(...))619 resp.set_cookie('username', 'the username')620 return resp621622Note that cookies are set on response objects. Since you normally623just return strings from the view functions Flask will convert them into624response objects for you. If you explicitly want to do that you can use625the :meth:`~flask.make_response` function and then modify it.626627Sometimes you might want to set a cookie at a point where the response628object does not exist yet. This is possible by utilizing the629:ref:`deferred-callbacks` pattern.630631For this also see :ref:`about-responses`.632633Redirects and Errors634--------------------635636To redirect a user to another endpoint, use the :func:`~flask.redirect`637function; to abort a request early with an error code, use the638:func:`~flask.abort` function::639640 from flask import abort, redirect, url_for641642 @app.route('/')643 def index():644 return redirect(url_for('login'))645646 @app.route('/login')647 def login():648 abort(401)649 this_is_never_executed()650651This is a rather pointless example because a user will be redirected from652the index to a page they cannot access (401 means access denied) but it653shows how that works.654655By default a black and white error page is shown for each error code. If656you want to customize the error page, you can use the657:meth:`~flask.Flask.errorhandler` decorator::658659 from flask import render_template660661 @app.errorhandler(404)662 def page_not_found(error):663 return render_template('page_not_found.html'), 404664665Note the ``404`` after the :func:`~flask.render_template` call. This666tells Flask that the status code of that page should be 404 which means667not found. By default 200 is assumed which translates to: all went well.668669See :ref:`error-handlers` for more details.670671.. _about-responses:672673About Responses674---------------675676The return value from a view function is automatically converted into a677response object for you. If the return value is a string it's converted678into a response object with the string as response body, a ``200 OK``679status code and a :mimetype:`text/html` mimetype. The logic that Flask applies to680converting return values into response objects is as follows:6816821. If a response object of the correct type is returned it's directly683 returned from the view.6842. If it's a string, a response object is created with that data and the685 default parameters.6863. If a tuple is returned the items in the tuple can provide extra687 information. Such tuples have to be in the form ``(response, status,688 headers)`` or ``(response, headers)`` where at least one item has

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

lines 706–731why, one step back
706
707 @app.errorhandler(404)708 def not_found(error):709 resp = make_response(render_template('error.html'), 404)710 resp.headers['X-Something'] = 'A value'711 return resp712713.. _sessions:714715Sessions716--------717718In addition to the request object there is also a second object called719:class:`~flask.session` which allows you to store information specific to a720user from one request to the next. This is implemented on top of cookies721for you and signs the cookies cryptographically. What this means is that722the user could look at the contents of your cookie but not modify it,723unless they know the secret key used for signing.724725In order to use sessions you have to set a secret key. Here is how726sessions work::727728 from flask import Flask, session, redirect, url_for, escape, request729730 app = Flask(__name__)731

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

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

lines 748–763why, one step back
748 <p><input type=text name=username>
749 <p><input type=submit value=Login>750 </form>751 '''752753 @app.route('/logout')754 def logout():755 # remove the username from the session if it's there756 session.pop('username', None)757 return redirect(url_for('index'))758759The :func:`~flask.escape` mentioned here does escaping for you if you are760not using the template engine (as in this example).761762.. admonition:: How to generate good secret keys763

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

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

line 768why, one step back
768

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

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

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

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Fix wordingDaniel Neuhäuserbefore adoption2b58e61

lines 781–851why, one step back
781
782Message Flashing783----------------784785Good applications and user interfaces are all about feedback. If the user786does not get enough feedback they will probably end up hating the787application. Flask provides a really simple way to give feedback to a788user with the flashing system. The flashing system basically makes it789possible to record a message at the end of a request and access it on the next790(and only the next) request. This is usually combined with a layout791template to expose the message.792793To flash a message use the :func:`~flask.flash` method, to get hold of the794messages you can use :func:`~flask.get_flashed_messages` which is also795available in the templates. Check out the :ref:`message-flashing-pattern`796for a full example.797798Logging799-------800801.. versionadded:: 0.3802803Sometimes you might be in a situation where you deal with data that804should be correct, but actually is not. For example you may have some client-side805code that sends an HTTP request to the server but it's obviously806malformed. This might be caused by a user tampering with the data, or the807client code failing. Most of the time it's okay to reply with ``400 Bad808Request`` in that situation, but sometimes that won't do and the code has809to continue working.810811You may still want to log that something fishy happened. This is where812loggers come in handy. As of Flask 0.3 a logger is preconfigured for you813to use.814815Here are some example log calls::816817 app.logger.debug('A value for debugging')818 app.logger.warning('A warning occurred (%d apples)', 42)819 app.logger.error('An error occurred')820821The attached :attr:`~flask.Flask.logger` is a standard logging822:class:`~logging.Logger`, so head over to the official `logging823documentation <https://docs.python.org/library/logging.html>`_ for more824information.825826Read more on :ref:`application-errors`.827828Hooking in WSGI Middlewares829---------------------------830831If you want to add a WSGI middleware to your application you can wrap the832internal WSGI application. For example if you want to use one of the833middlewares from the Werkzeug package to work around bugs in lighttpd, you834can do it like this::835836 from werkzeug.contrib.fixers import LighttpdCGIRootFix837 app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)838839Using Flask Extensions840----------------------841842Extensions are packages that help you accomplish common tasks. For843example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple844and easy to use with Flask.845846For more on Flask extensions, have a look at :ref:`extensions`.847848Deploying to a Web Server849-------------------------850851Ready to deploy your new Flask app? Go to :ref:`deployment`.