quickstart.rst
This file
Path
docs/quickstart.rst
846 lines · 30.2 KiB
Last changed by
Merge pull request #2399 from davidism/docs-secret-keyDavid Lordbefore adoptiond13e41d
History of this fileTake it
The walk stopped after 200 commits: lines older than 773ad9b point at it.
Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 1–20why, one step back1.. _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 back21 return 'Hello, World!'Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 22–28why, one step back2223So 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 (asresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 29why, one step back29 in this example), you should use ``__name__`` because depending on if it'sMerge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 30–39why, one step back30 started as application or imported as module the name will be different31 (``'__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.39resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 40–42why, one step back40Just save it as :file:`hello.py` or something similar. Make sure to not call41your application :file:`flask.py` because this would conflict with Flask42itself.Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
line 43why, one step back43Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894
line 44why, one step back44To run the application you can either use the :command:`flask` command orresolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 45–47why, one step back45python's ``-m`` switch with Flask. Before you can do that you need46to 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 back48resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 49–50why, one step back49 $ export FLASK_APP=hello.py50 $ flask runMerge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894
lines 51–52why, one step back51 * Running on http://127.0.0.1:5000/52resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 53–54why, one step back53If you are on Windows, the environment variable syntax depends on command line54interpreter. On Command Prompt::Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894
line 55why, one step back55resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 56–65why, one step back56 C:\path\to\app>set FLASK_APP=hello.py5758And 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 runMerge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894
lines 66–74why, one step back66 * 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.74Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 75–87why, one step back75.. _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::87resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 88why, one step back88 flask run --host=0.0.0.0Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 89–91why, one step back8990 This tells your operating system to listen on all public IPs.91Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894
line 92why, one step back92Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 93–95why, one step back93What to do if the Server does not Start94---------------------------------------95resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 96why, one step back96In case the :command:`python -m flask` fails or :command:`flask` does not exist,Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 97–102why, one step back97there are multiple reasons this might be the case. First of all you need98to look at the error message.99100Old Version of Flask101````````````````````102resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 103why, one step back103Versions of Flask older than 0.11 use to have different ways to start theMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 104why, one step back104application. In short, the :command:`flask` command did not exist, andresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 105why, one step back105neither did :command:`python -m flask`. In that case you have two options:Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 106–111why, one step back106either 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```````````````````111resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 112–115why, one step back112The ``FLASK_APP`` environment variable is the name of the module to import at113: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 #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 116–124why, one step back116117The most common reason is a typo or because you did not actually create an118``app`` object.119120.. _debug-mode:121122Debug Mode123----------124resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 125–126why, one step back125(Want to just log errors and stack traces? See :ref:`application-errors`)126Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 127why, one step back127The :command:`flask` script is nice to start a local development server, butMerge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 128–132why, one step back128you 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.132resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 133–134why, one step back133To enable debug mode you can export the ``FLASK_DEBUG`` environment variable134before running the server::Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
line 135why, one step back135resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 136–137why, one step back136 $ export FLASK_DEBUG=1137 $ flask runMerge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
line 138why, one step back138resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 139–140why, one step back139(On Windows you need to use ``set`` instead of ``export``).140Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 141–162why, one step back141This does the following things:1421431. it activates the debugger1442. it activates the automatic reloader1453. it enables the debug mode on the Flask application.146147There are more parameters that are explained in the :ref:`server` docs.148149.. admonition:: Attention150151 Even though the interactive debugger does not work in forking environments152 (which makes it nearly impossible to use on production servers), it still153 allows the execution of arbitrary code. This makes it a major security risk154 and therefore it **must never be used on production machines**.155156Screenshot of the debugger in action:157158.. image:: _static/debugger.png159 :align: center160 :class: screenshot161 :alt: screenshot of debugger in action162Merge pull request #2399 from davidism/docs-secret-keyDavid Lordbefore adoptiond13e41d
line 163why, one step back163More information on using the debugger can be found in the `Werkzeugresolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 164–167why, one step back164documentation`_.165166.. _Werkzeug documentation: http://werkzeug.pocoo.org/docs/debug/#using-the-debugger167Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 168–173why, one step back168Have another debugger in mind? See :ref:`working-with-debuggers`.169170171Routing172-------173resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 174–176why, one step back174Modern web applications use meaningful URLs to help users. Users are more175likely to like a page and come back if the page uses a meaningful URL they can176remember and use to directly visit a page.Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
line 177why, one step back177resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 178why, one step back178Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. ::Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 179–185why, one step back179180 @app.route('/')181 def index():182 return 'Index Page'183184 @app.route('/hello')185 def hello():Merge pull request #1318 from cerivera/masterMarkus Unterwaditzerbefore adoptione3ba459
line 186why, one step back186 return 'Hello, World'Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
line 187why, one step back187resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 188–189why, one step back188You can do more! You can make parts of the URL dynamic and attach multiple189rules to a function.Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 190–193why, one step back190191Variable Rules192``````````````193resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 194–197why, one step back194You can add variable sections to a URL by marking sections with195``<variable_name>``. Your function then receives the ``<variable_name>``196as a keyword argument. Optionally, you can use a converter to specify the type197of the argument like ``<converter:variable_name>``. ::Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 198–208why, one step back198199 @app.route('/user/<username>')200 def show_user_profile(username):201 # show the user profile for that user202 return 'User %s' % username203204 @app.route('/post/<int:post_id>')205 def show_post(post_id):206 # show the post with the given id, the id is an integer207 return 'Post %d' % post_id208resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 209–212why, one step back209 @app.route('/path/<path:subpath>')210 def show_subpath(subpath):211 # show the subpath after /path/212 return 'Subpath %s' % subpathMerge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
line 213why, one step back213resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 214why, one step back214Converter types:Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
line 215why, one step back215resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 216–222why, one step back216========== ==========================================217``string`` (default) accepts any text without a slash218``int`` accepts positive integers219``float`` accepts positive floating point values220``path`` like ``string`` but also accepts slashes221``uuid`` accepts UUID strings222========== ==========================================Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
line 223why, one step back223resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 224–225why, one step back224Unique URLs / Redirection Behavior225``````````````````````````````````Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
line 226why, one step back226resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 227why, one step back227Take these two rules::Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
line 228why, one step back228resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 229–231why, one step back229 @app.route('/projects/')230 def projects():231 return 'The project page'Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
line 232why, one step back232resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 233–235why, one step back233 @app.route('/about')234 def about():235 return 'The about page'Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
line 236why, one step back236resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 237–241why, one step back237Though they look similar, they differ in their use of the trailing slash in238the URL. In the first case, the canonical URL for the ``projects`` endpoint239uses a trailing slash. It's similar to a folder in a file system; if you240access the URL without a trailing slash, Flask redirects you to the241canonical URL with the trailing slash.Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
line 242why, one step back242resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 243–245why, one step back243In the second case, however, the URL definition lacks a trailing slash,244like the pathname of a file on UNIX-like systems. Accessing the URL with a245trailing slash produces a 404 “Not Found” error.Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
line 246why, one step back246resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 247–250why, one step back247This behavior allows relative URLs to continue working even if the trailing248slash is omitted, consistent with how Apache and other servers work. Also,249the URLs will stay unique, which helps search engines avoid indexing the250same page twice.Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 251–256why, one step back251252.. _url-building:253254URL Building255````````````256resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 257–260why, one step back257To build a URL to a specific function, use the :func:`~flask.url_for` function.258It accepts the name of the function as its first argument and any number of259keyword arguments, each corresponding to a variable part of the URL rule.260Unknown variable parts are appended to the URL as query parameters.Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 261–264why, one step back261262Why would you want to build URLs using the URL reversing function263:func:`~flask.url_for` instead of hard-coding them into your templates?264resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 265–272why, one step back2651. Reversing is often more descriptive than hard-coding the URLs.2662. You can change your URLs in one go instead of needing to remember to267 manually change hard-coded URLs.2683. URL building handles escaping of special characters and Unicode data269 transparently.2704. If your application is placed outside the URL root, for example, in271 ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly272 handles that for you.Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
line 273why, one step back273resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 274–277why, one step back274For example, here we use the :meth:`~flask.Flask.test_request_context` method275to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context`276tells Flask to behave as though it's handling a request even while we use a277Python shell. See :ref:`context-locals`. ::Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
line 278why, one step back278resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 279–305why, one step back279 from flask import Flask, url_for280281 app = Flask(__name__)282283 @app.route('/')284 def index():285 return 'index'286287 @app.route('/login')288 def login():289 return 'login'290291 @app.route('/user/<username>')292 def profile(username):293 return '{}'s profile'.format(username)294295 with app.test_request_context():296 print(url_for('index'))297 print(url_for('login'))298 print(url_for('login', next='/'))299 print(url_for('profile', username='John Doe'))300301 /302 /login303 /login?next=/304 /user/John%20Doe305Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 306–308why, one step back306HTTP Methods307````````````308resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 309–313why, one step back309Web applications use different HTTP methods when accessing URLs. You should310familiarize yourself with the HTTP methods as you work with Flask. By default,311a route only answers to ``GET`` requests. You can use the ``methods`` argument312of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods.313::Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 314–321why, one step back314315 @app.route('/login', methods=['GET', 'POST'])316 def login():317 if request.method == 'POST':318 do_the_login()319 else:320 show_the_login_form()321resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 322–324why, one step back322If ``GET`` is present, Flask automatically adds support for the ``HEAD`` method323and handles ``HEAD`` requests according to the the `HTTP RFC`_. Likewise,324``OPTIONS`` is automatically implemented for you.Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
line 325why, one step back325resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 326why, one step back326.. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txtMerge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 327–333why, one step back327328Static Files329------------330331Dynamic web applications also need static files. That's usually where332the CSS and JavaScript files are coming from. Ideally your web server is333configured to serve them for you, but during development Flask can do thatMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
lines 334–335why, one step back334as well. Just create a folder called :file:`static` in your package or next to335your module and it will be available at ``/static`` on the application.Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 336–340why, one step back336337To generate URLs for static files, use the special ``'static'`` endpoint name::338339 url_for('static', filename='style.css')340Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 341why, one step back341The file has to be stored on the filesystem as :file:`static/style.css`.Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 342–362why, one step back342343Rendering Templates344-------------------345346Generating HTML from within Python is not fun, and actually pretty347cumbersome because you have to do the HTML escaping on your own to keep348the application secure. Because of that Flask configures the `Jinja2349<http://jinja.pocoo.org/>`_ template engine for you automatically.350351To render a template you can use the :func:`~flask.render_template`352method. All you have to do is provide the name of the template and the353variables you want to pass to the template engine as keyword arguments.354Here's a simple example of how to render a template::355356 from flask import render_template357358 @app.route('/hello/')359 @app.route('/hello/<name>')360 def hello(name=None):361 return render_template('hello.html', name=name)362Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 363why, one step back363Flask will look for templates in the :file:`templates` folder. So if yourMerge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 364–392why, one step back364application is a module, this folder is next to that module, if it's a365package it's actually inside your package:366367**Case 1**: a module::368369 /application.py370 /templates371 /hello.html372373**Case 2**: a package::374375 /application376 /__init__.py377 /templates378 /hello.html379380For templates you can use the full power of Jinja2 templates. Head over381to the official `Jinja2 Template Documentation382<http://jinja.pocoo.org/docs/templates>`_ for more information.383384Here is an example template:385386.. sourcecode:: html+jinja387388 <!doctype html>389 <title>Hello from Flask</title>390 {% if name %}391 <h1>Hello {{ name }}!</h1>392 {% else %}Merge pull request #1318 from cerivera/masterMarkus Unterwaditzerbefore adoptione3ba459
line 393why, one step back393 <h1>Hello, World!</h1>Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 394–404why, one step back394 {% endif %}395396Inside templates you also have access to the :class:`~flask.request`,397:class:`~flask.session` and :class:`~flask.g` [#]_ objects398as well as the :func:`~flask.get_flashed_messages` function.399400Templates are especially useful if inheritance is used. If you want to401know how that works, head over to the :ref:`template-inheritance` pattern402documentation. Basically template inheritance makes it possible to keep403certain elements on each page (like header, navigation and footer).404resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 405why, one step back405Automatic escaping is enabled, so if ``name`` contains HTML it will be escapedMerge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 406–411why, one step back406automatically. If you can trust a variable and you know that it will be407safe HTML (for example because it came from a module that converts wiki408markup to HTML) you can mark it as safe by using the409:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the410template. Head over to the Jinja 2 documentation for more examples.411resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 412why, one step back412Here is a basic introduction to how the :class:`~jinja2.Markup` class works::Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
line 413why, one step back413resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 414–420why, one step back414 >>> from flask import Markup415 >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'416 Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')417 >>> Markup.escape('<blink>hacker</blink>')418 Markup(u'<blink>hacker</blink>')419 >>> Markup('<em>Marked up</em> » HTML').striptags()420 u'Marked up \xbb HTML'Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 421–437why, one step back421422.. versionchanged:: 0.5423424 Autoescaping is no longer enabled for all templates. The following425 extensions for templates trigger autoescaping: ``.html``, ``.htm``,426 ``.xml``, ``.xhtml``. Templates loaded from a string will have427 autoescaping disabled.428429.. [#] Unsure what that :class:`~flask.g` object is? It's something in which430 you can store information for your own needs, check the documentation of431 that object (:class:`~flask.g`) and the :ref:`sqlite3` for more432 information.433434435Accessing Request Data436----------------------437Merge pull request #1299 from sateeshkumarb/patch-1Markus Unterwaditzerbefore adoption4fde65e
line 438why, one step back438For web applications it's crucial to react to the data a client sends toMerge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 439–473why, one step back439the server. In Flask this information is provided by the global440:class:`~flask.request` object. If you have some experience with Python441you might be wondering how that object can be global and how Flask442manages to still be threadsafe. The answer is context locals:443444445.. _context-locals:446447Context Locals448``````````````449450.. admonition:: Insider Information451452 If you want to understand how that works and how you can implement453 tests with context locals, read this section, otherwise just skip it.454455Certain objects in Flask are global objects, but not of the usual kind.456These objects are actually proxies to objects that are local to a specific457context. What a mouthful. But that is actually quite easy to understand.458459Imagine the context being the handling thread. A request comes in and the460web server decides to spawn a new thread (or something else, the461underlying object is capable of dealing with concurrency systems other462than threads). When Flask starts its internal request handling it463figures out that the current thread is the active context and binds the464current application and the WSGI environments to that context (thread).465It does that in an intelligent way so that one application can invoke another466application without breaking.467468So what does this mean to you? Basically you can completely ignore that469this is the case unless you are doing something like unit testing. You470will notice that code which depends on a request object will suddenly break471because there is no request object. The solution is creating a request472object yourself and binding it to the context. The easiest solution for473unit testing is to use the :meth:`~flask.Flask.test_request_context`Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 474why, one step back474context manager. In combination with the ``with`` statement it will bind aMerge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 475–496why, one step back475test request so that you can interact with it. Here is an example::476477 from flask import request478479 with app.test_request_context('/hello', method='POST'):480 # now you can do something with the request until the481 # end of the with block, such as basic assertions:482 assert request.path == '/hello'483 assert request.method == 'POST'484485The other possibility is passing a whole WSGI environment to the486:meth:`~flask.Flask.request_context` method::487488 from flask import request489490 with app.request_context(environ):491 assert request.method == 'POST'492493The Request Object494``````````````````495496The request object is documented in the API section and we will not coverresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 497why, one step back497it here in detail (see :class:`~flask.Request`). Here is a broad overview ofMerge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
line 498why, one step back498some of the most common operations. First of all you have to import it fromresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 499why, one step back499the ``flask`` module::Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 500–503why, one step back500501 from flask import request502503The current request method is available by using theresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 504why, one step back504:attr:`~flask.Request.method` attribute. To access form data (dataMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 505why, one step back505transmitted in a ``POST`` or ``PUT`` request) you can use theresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 506why, one step back506:attr:`~flask.Request.form` attribute. Here is a full example of the twoMerge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 507–521why, one step back507attributes mentioned above::508509 @app.route('/login', methods=['POST', 'GET'])510 def login():511 error = None512 if request.method == 'POST':513 if valid_login(request.form['username'],514 request.form['password']):515 return log_the_user_in(request.form['username'])516 else:517 error = 'Invalid username/password'518 # the code below is executed if the request method519 # was GET or the credentials were invalid520 return render_template('login.html', error=error)521resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 522why, one step back522What happens if the key does not exist in the ``form`` attribute? In thatMerge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 523–528why, one step back523case a special :exc:`KeyError` is raised. You can catch it like a524standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request525error page is shown instead. So for many situations you don't have to526deal with that problem.527528To access parameters submitted in the URL (``?key=value``) you can use theresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 529why, one step back529:attr:`~flask.Request.args` attribute::Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 530–533why, one step back530531 searchword = request.args.get('key', '')532533We recommend accessing URL parameters with `get` or by catching theMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 534why, one step back534:exc:`KeyError` because users might change the URL and presenting them a 400Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 535–537why, one step back535bad request page in that case is not user friendly.536537For a full list of methods and attributes of the request object, head overresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 538why, one step back538to the :class:`~flask.Request` documentation.Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 539–574why, one step back539540541File Uploads542````````````543544You can handle uploaded files with Flask easily. Just make sure not to545forget to set the ``enctype="multipart/form-data"`` attribute on your HTML546form, otherwise the browser will not transmit your files at all.547548Uploaded files are stored in memory or at a temporary location on the549filesystem. You can access those files by looking at the550:attr:`~flask.request.files` attribute on the request object. Each551uploaded file is stored in that dictionary. It behaves just like a552standard Python :class:`file` object, but it also has a553:meth:`~werkzeug.datastructures.FileStorage.save` method that allows you to store that554file on the filesystem of the server. Here is a simple example showing how555that works::556557 from flask import request558559 @app.route('/upload', methods=['GET', 'POST'])560 def upload_file():561 if request.method == 'POST':562 f = request.files['the_file']563 f.save('/var/www/uploads/uploaded_file.txt')564 ...565566If you want to know how the file was named on the client before it was567uploaded to your application, you can access the568:attr:`~werkzeug.datastructures.FileStorage.filename` attribute. However please keep in569mind that this value can be forged so never ever trust that value. If you570want to use the filename of the client to store the file on the server,571pass it through the :func:`~werkzeug.utils.secure_filename` function that572Werkzeug provides for you::573574 from flask import requestMerge pull request #1461 from justinwp/patch-1Markus Unterwaditzerbefore adoption1e15e17
line 575why, one step back575 from werkzeug.utils import secure_filenameMerge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 576–663why, one step back576577 @app.route('/upload', methods=['GET', 'POST'])578 def upload_file():579 if request.method == 'POST':580 f = request.files['the_file']581 f.save('/var/www/uploads/' + secure_filename(f.filename))582 ...583584For some better examples, checkout the :ref:`uploading-files` pattern.585586Cookies587```````588589To access cookies you can use the :attr:`~flask.Request.cookies`590attribute. To set cookies you can use the591:attr:`~flask.Response.set_cookie` method of response objects. The592:attr:`~flask.Request.cookies` attribute of request objects is a593dictionary with all the cookies the client transmits. If you want to use594sessions, do not use the cookies directly but instead use the595:ref:`sessions` in Flask that add some security on top of cookies for you.596597Reading cookies::598599 from flask import request600601 @app.route('/')602 def index():603 username = request.cookies.get('username')604 # use cookies.get(key) instead of cookies[key] to not get a605 # KeyError if the cookie is missing.606607Storing cookies::608609 from flask import make_response610611 @app.route('/')612 def index():613 resp = make_response(render_template(...))614 resp.set_cookie('username', 'the username')615 return resp616617Note that cookies are set on response objects. Since you normally618just return strings from the view functions Flask will convert them into619response objects for you. If you explicitly want to do that you can use620the :meth:`~flask.make_response` function and then modify it.621622Sometimes you might want to set a cookie at a point where the response623object does not exist yet. This is possible by utilizing the624:ref:`deferred-callbacks` pattern.625626For this also see :ref:`about-responses`.627628Redirects and Errors629--------------------630631To redirect a user to another endpoint, use the :func:`~flask.redirect`632function; to abort a request early with an error code, use the633:func:`~flask.abort` function::634635 from flask import abort, redirect, url_for636637 @app.route('/')638 def index():639 return redirect(url_for('login'))640641 @app.route('/login')642 def login():643 abort(401)644 this_is_never_executed()645646This is a rather pointless example because a user will be redirected from647the index to a page they cannot access (401 means access denied) but it648shows how that works.649650By default a black and white error page is shown for each error code. If651you want to customize the error page, you can use the652:meth:`~flask.Flask.errorhandler` decorator::653654 from flask import render_template655656 @app.errorhandler(404)657 def page_not_found(error):658 return render_template('page_not_found.html'), 404659660Note the ``404`` after the :func:`~flask.render_template` call. This661tells Flask that the status code of that page should be 404 which means662not found. By default 200 is assumed which translates to: all went well.663Merge pull request #1429 from flying-sheep/errorhandler-rework-docsMarkus Unterwaditzerbefore adoption06f2be3
lines 664–665why, one step back664See :ref:`error-handlers` for more details.665Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 666–673why, one step back666.. _about-responses:667668About Responses669---------------670671The return value from a view function is automatically converted into a672response object for you. If the return value is a string it's converted673into 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 674why, one step back674status code and a :mimetype:`text/html` mimetype. The logic that Flask applies toMerge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 675–683why, one step back675converting return values into response objects is as follows:6766771. If a response object of the correct type is returned it's directly678 returned from the view.6792. If it's a string, a response object is created with that data and the680 default parameters.6813. If a tuple is returned the items in the tuple can provide extra682 information. Such tuples have to be in the form ``(response, status,683 headers)`` or ``(response, headers)`` where at least one item hasresolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 684–685why, one step back684 to be in the tuple. The ``status`` value will override the status code685 and ``headers`` can be a list or dictionary of additional header values.Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 686–691why, one step back6864. If none of that works, Flask will assume the return value is a687 valid WSGI application and convert that into a response object.688689If you want to get hold of the resulting response object inside the view690you can use the :func:`~flask.make_response` function.691resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 692why, one step back692Imagine you have a view like this::Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 693–699why, one step back693694 @app.errorhandler(404)695 def not_found(error):696 return render_template('error.html'), 404697698You just need to wrap the return expression with699:func:`~flask.make_response` and get the response object to modify it, thenresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 700why, one step back700return it::Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 701–726why, one step back701702 @app.errorhandler(404)703 def not_found(error):704 resp = make_response(render_template('error.html'), 404)705 resp.headers['X-Something'] = 'A value'706 return resp707708.. _sessions:709710Sessions711--------712713In addition to the request object there is also a second object called714:class:`~flask.session` which allows you to store information specific to a715user from one request to the next. This is implemented on top of cookies716for you and signs the cookies cryptographically. What this means is that717the user could look at the contents of your cookie but not modify it,718unless they know the secret key used for signing.719720In order to use sessions you have to set a secret key. Here is how721sessions work::722723 from flask import Flask, session, redirect, url_for, escape, request724725 app = Flask(__name__)726Merge pull request #2399 from davidism/docs-secret-keyDavid Lordbefore adoptiond13e41d
lines 727–729why, one step back727 # Set the secret key to some random bytes. Keep this really secret!728 app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'729Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 730–741why, one step back730 @app.route('/')731 def index():732 if 'username' in session:733 return 'Logged in as %s' % escape(session['username'])734 return 'You are not logged in'735736 @app.route('/login', methods=['GET', 'POST'])737 def login():738 if request.method == 'POST':739 session['username'] = request.form['username']740 return redirect(url_for('index'))741 return '''resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 742why, one step back742 <form method="post">Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 743–758why, one step back743 <p><input type=text name=username>744 <p><input type=submit value=Login>745 </form>746 '''747748 @app.route('/logout')749 def logout():750 # remove the username from the session if it's there751 session.pop('username', None)752 return redirect(url_for('index'))753754The :func:`~flask.escape` mentioned here does escaping for you if you are755not using the template engine (as in this example).756757.. admonition:: How to generate good secret keys758Merge pull request #2399 from davidism/docs-secret-keyDavid Lordbefore adoptiond13e41d
lines 759–762why, one step back759 A secret key should be as random as possible. Your operating system has760 ways to generate pretty random data based on a cryptographic random761 generator. Use the following command to quickly generate a value for762 :attr:`Flask.secret_key` (or :data:`SECRET_KEY`)::Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
line 763why, one step back763Merge pull request #2399 from davidism/docs-secret-keyDavid Lordbefore adoptiond13e41d
lines 764–765why, one step back764 $ python -c 'import os; print(os.urandom(16))'765 b'_5#y2L"F4Q8z\n\xec]/'Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 766–772why, one step back766767A note on cookie-based sessions: Flask will take the values you put into the768session object and serialize them into a cookie. If you are finding some769values do not persist across requests, cookies are indeed enabled, and you are770not getting a clear error message, check the size of the cookie in your page771responses compared to the size supported by web browsers.772resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 773–775why, one step back773Besides the default client-side based sessions, if you want to handle774sessions on the server-side instead, there are several775Flask extensions that support this.Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 776–820why, one step back776777Message Flashing778----------------779780Good applications and user interfaces are all about feedback. If the user781does not get enough feedback they will probably end up hating the782application. Flask provides a really simple way to give feedback to a783user with the flashing system. The flashing system basically makes it784possible to record a message at the end of a request and access it on the next785(and only the next) request. This is usually combined with a layout786template to expose the message.787788To flash a message use the :func:`~flask.flash` method, to get hold of the789messages you can use :func:`~flask.get_flashed_messages` which is also790available in the templates. Check out the :ref:`message-flashing-pattern`791for a full example.792793Logging794-------795796.. versionadded:: 0.3797798Sometimes you might be in a situation where you deal with data that799should be correct, but actually is not. For example you may have some client-side800code that sends an HTTP request to the server but it's obviously801malformed. This might be caused by a user tampering with the data, or the802client code failing. Most of the time it's okay to reply with ``400 Bad803Request`` in that situation, but sometimes that won't do and the code has804to continue working.805806You may still want to log that something fishy happened. This is where807loggers come in handy. As of Flask 0.3 a logger is preconfigured for you808to use.809810Here are some example log calls::811812 app.logger.debug('A value for debugging')813 app.logger.warning('A warning occurred (%d apples)', 42)814 app.logger.error('An error occurred')815816The attached :attr:`~flask.Flask.logger` is a standard logging817:class:`~logging.Logger`, so head over to the official `logging818documentation <https://docs.python.org/library/logging.html>`_ for more819information.820Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894
lines 821–822why, one step back821Read more on :ref:`application-errors`.822Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 823–833why, one step back823Hooking in WSGI Middlewares824---------------------------825826If you want to add a WSGI middleware to your application you can wrap the827internal WSGI application. For example if you want to use one of the828middlewares from the Werkzeug package to work around bugs in lighttpd, you829can do it like this::830831 from werkzeug.contrib.fixers import LighttpdCGIRootFix832 app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)833Merge pull request #1376 from KWinston/masterMarkus Unterwaditzerbefore adoptionec5811d
lines 834–842why, one step back834Using Flask Extensions835----------------------836837Extensions are packages that help you accomplish common tasks. For838example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple839and easy to use with Flask.840841For more on Flask extensions, have a look at :ref:`extensions`.842Merge pull request #1172 from cgar/spellingMarkus Unterwaditzerbefore adoption773ad9b
lines 843–845why, one step back843Deploying to a Web Server844-------------------------845Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894
line 846why, one step back846Ready to deploy your new Flask app? Go to :ref:`deployment`.