quickstart.rst
This file
Path
docs/quickstart.rst
919 lines · 31.7 KiB
Last changed by
remove unused ref directivesDavid Lordbefore adoption171aabc
History of this fileTake it
The walk stopped after 200 commits: lines older than 324b4ea point at it.
Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 1–3why, one step back1Quickstart2==========3Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
lines 4–5why, one step back4Eager to get started? This page gives a good introduction to Flask.5Follow :doc:`installation` to set up a project and install Flask first.Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 6–10why, one step back678A Minimal Application9---------------------10Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 11why, one step back11A minimal Flask application looks something like this:Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
line 12why, one step back12Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
lines 13–14why, one step back13.. code-block:: python14Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
line 15why, one step back15 from flask import FlaskMerge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 16why, one step back16Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 17–18why, one step back17 app = Flask(__name__)18Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 19why, one step back19 @app.route("/")Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
line 20why, one step back20 def hello_world():Merge pull request #3529 from pgkrit/masterDavid Lordbefore adoption3d61fc4
line 21why, one step back21 return "<p>Hello, World!</p>"Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 22–24why, one step back2223So what did that code do?24Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
lines 25–36why, one step back251. First we imported the :class:`~flask.Flask` class. An instance of26 this class will be our WSGI application.272. Next we create an instance of this class. The first argument is the28 name of the application's module or package. ``__name__`` is a29 convenient shortcut for this that is appropriate for most cases.30 This is needed so that Flask knows where to look for resources such31 as templates and static files.323. We then use the :meth:`~flask.Flask.route` decorator to tell Flask33 what URL should trigger our function.344. The function returns the message we want to display in the user's35 browser. The default content type is HTML, so HTML in the string36 will be rendered by the browser.Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
line 37why, one step back37Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 38why, one step back38Save it as :file:`hello.py` or something similar. Make sure to not callMerge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 39–41why, one step back39your application :file:`flask.py` because this would conflict with Flask40itself.41Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
lines 42–43why, one step back42To run the application, use the :command:`flask` command or43:command:`python -m flask`. Before you can do that you needMerge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
line 44why, one step back44to tell your terminal the application to work with by exporting theMerge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 45why, one step back45``FLASK_APP`` environment variable:Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
line 46why, one step back46Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
lines 47–48why, one step back47.. code-block:: text48Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 49–61why, one step back49 $ export FLASK_APP=hello.py50 $ flask run51 * Running on http://127.0.0.1:5000/5253If you are on Windows, the environment variable syntax depends on command line54interpreter. On Command Prompt::5556 C:\path\to\app>set FLASK_APP=hello.py5758And on PowerShell::5960 PS C:\path\to\app> $env:FLASK_APP = "hello.py"61remove unused ref directivesDavid Lordbefore adoption171aabc
lines 62–64why, one step back62This launches a very simple builtin server, which is good enough for63testing but probably not what you want to use in production. For64deployment options see :doc:`deploying/index`.Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
line 65why, one step back65Merge branch '1.0.x'David Lordbefore adoption1351d0a
lines 66–67why, one step back66Now head over to http://127.0.0.1:5000/, and you should see your hello67world greeting.Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 68–81why, one step back6869.. _public-server:7071.. admonition:: Externally Visible Server7273 If you run the server you will notice that the server is only accessible74 from your own computer, not from any other in the network. This is the75 default because in debugging mode a user of the application can execute76 arbitrary Python code on your computer.7778 If you have the debugger disabled or trust the users on your network,79 you can make the server publicly available simply by adding80 ``--host=0.0.0.0`` to the command line::81Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6
line 82why, one step back82 $ flask run --host=0.0.0.0Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 83–89why, one step back8384 This tells your operating system to listen on all public IPs.858687What to do if the Server does not Start88---------------------------------------89Merge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
lines 90–92why, one step back90In case the :command:`python -m flask` fails or :command:`flask`91does not exist, there are multiple reasons this might be the case.92First of all you need to look at the error message.Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 93–99why, one step back9394Old Version of Flask95````````````````````9697Versions of Flask older than 0.11 use to have different ways to start the98application. In short, the :command:`flask` command did not exist, and99neither did :command:`python -m flask`. In that case you have two options:Merge pull request #3434 from pallets/eager-loadDavid Lordbefore adoptionbfa9ace
lines 100–101why, one step back100either upgrade to newer Flask versions or have a look at :doc:`/server`101to see the alternative method for running a server.Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 102–118why, one step back102103Invalid Import Name104```````````````````105106The ``FLASK_APP`` environment variable is the name of the module to import at107:command:`flask run`. In case that module is incorrectly named you will get an108import error upon start (or if debug is enabled when you navigate to the109application). It will tell you what it tried to import and why it failed.110111The most common reason is a typo or because you did not actually create an112``app`` object.113114.. _debug-mode:115116Debug Mode117----------118remove unused ref directivesDavid Lordbefore adoption171aabc
line 119why, one step back119(Want to just log errors and stack traces? See :doc:`errorhandling`)Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 120–144why, one step back120121The :command:`flask` script is nice to start a local development server, but122you would have to restart it manually after each change to your code.123That is not very nice and Flask can do better. If you enable debug124support the server will reload itself on code changes, and it will also125provide you with a helpful debugger if things go wrong.126127To enable all development features (including debug mode) you can export128the ``FLASK_ENV`` environment variable and set it to ``development``129before running the server::130131 $ export FLASK_ENV=development132 $ flask run133134(On Windows you need to use ``set`` instead of ``export``.)135136This does the following things:1371381. it activates the debugger1392. it activates the automatic reloader1403. it enables the debug mode on the Flask application.141142You can also control debug mode separately from the environment by143exporting ``FLASK_DEBUG=1``.144Merge pull request #3434 from pallets/eager-loadDavid Lordbefore adoptionbfa9ace
line 145why, one step back145There are more parameters that are explained in :doc:`/server`.Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 146–163why, one step back146147.. admonition:: Attention148149 Even though the interactive debugger does not work in forking environments150 (which makes it nearly impossible to use on production servers), it still151 allows the execution of arbitrary code. This makes it a major security risk152 and therefore it **must never be used on production machines**.153154Screenshot of the debugger in action:155156.. image:: _static/debugger.png157 :align: center158 :class: screenshot159 :alt: screenshot of debugger in action160161More information on using the debugger can be found in the `Werkzeug162documentation`_.163Merge branch '1.0.x'David Lordbefore adoption1351d0a
line 164why, one step back164.. _Werkzeug documentation: https://werkzeug.palletsprojects.com/debug/#using-the-debuggerMerge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 165–168why, one step back165166Have another debugger in mind? See :ref:`working-with-debuggers`.167168Merge pull request #3529 from pgkrit/masterDavid Lordbefore adoption3d61fc4
lines 169–196why, one step back169HTML Escaping170-------------171172When returning HTML (the default response type in Flask), any173user-provided values rendered in the output must be escaped to protect174from injection attacks. HTML templates rendered with Jinja, introduced175later, will do this automatically.176177:func:`~markupsafe.escape`, shown here, can be used manually. It is178omitted in most examples for brevity, but you should always be aware of179how you're using untrusted data.180181.. code-block:: python182183 from markupsafe import escape184185 @app.route("/<name>")186 def hello(name):187 return f"Hello, {escape(name)}!"188189If a user managed to submit the name ``<script>alert("bad")</script>``,190escaping causes it to be rendered as text, rather than running the191script in the user's browser.192193``<name>`` in the route captures a value from the URL and passes it to194the view function. These variable rules are explained below.195196Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 197–224why, one step back197Routing198-------199200Modern web applications use meaningful URLs to help users. Users are more201likely to like a page and come back if the page uses a meaningful URL they can202remember and use to directly visit a page.203204Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. ::205206 @app.route('/')207 def index():208 return 'Index Page'209210 @app.route('/hello')211 def hello():212 return 'Hello, World'213214You can do more! You can make parts of the URL dynamic and attach multiple215rules to a function.216217Variable Rules218``````````````219220You can add variable sections to a URL by marking sections with221``<variable_name>``. Your function then receives the ``<variable_name>``222as a keyword argument. Optionally, you can use a converter to specify the type223of the argument like ``<converter:variable_name>``. ::224Merge remote-tracking branch 'origin/1.1.x'David Lordbefore adoption07556da
lines 225–226why, one step back225 from markupsafe import escape226Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 227–229why, one step back227 @app.route('/user/<username>')228 def show_user_profile(username):229 # show the user profile for that userMerge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 230why, one step back230 return f'User {username}'Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 231–234why, one step back231232 @app.route('/post/<int:post_id>')233 def show_post(post_id):234 # show the post with the given id, the id is an integerMerge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 235why, one step back235 return f'Post {post_id}'Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 236–239why, one step back236237 @app.route('/path/<path:subpath>')238 def show_subpath(subpath):239 # show the subpath after /path/Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 240why, one step back240 return f'Subpath {subpath}'Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 241–250why, one step back241242Converter types:243244========== ==========================================245``string`` (default) accepts any text without a slash246``int`` accepts positive integers247``float`` accepts positive floating point values248``path`` like ``string`` but also accepts slashes249``uuid`` accepts UUID strings250========== ==========================================Merge pull request #3529 from pgkrit/masterDavid Lordbefore adoption3d61fc4
line 251why, one step back251Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 252–292why, one step back252253Unique URLs / Redirection Behavior254``````````````````````````````````255256The following two rules differ in their use of a trailing slash. ::257258 @app.route('/projects/')259 def projects():260 return 'The project page'261262 @app.route('/about')263 def about():264 return 'The about page'265266The canonical URL for the ``projects`` endpoint has a trailing slash.267It's similar to a folder in a file system. If you access the URL without268a trailing slash, Flask redirects you to the canonical URL with the269trailing slash.270271The canonical URL for the ``about`` endpoint does not have a trailing272slash. It's similar to the pathname of a file. Accessing the URL with a273trailing slash produces a 404 "Not Found" error. This helps keep URLs274unique for these resources, which helps search engines avoid indexing275the same page twice.276277278.. _url-building:279280URL Building281````````````282283To build a URL to a specific function, use the :func:`~flask.url_for` function.284It accepts the name of the function as its first argument and any number of285keyword arguments, each corresponding to a variable part of the URL rule.286Unknown variable parts are appended to the URL as query parameters.287288Why would you want to build URLs using the URL reversing function289:func:`~flask.url_for` instead of hard-coding them into your templates?2902911. Reversing is often more descriptive than hard-coding the URLs.2922. You can change your URLs in one go instead of needing to remember toMerge pull request #3101 from tbm/docs-formattingDavid Lordbefore adoptionc795adf
line 293why, one step back293 manually change hard-coded URLs.Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374
line 294why, one step back2943. URL building handles escaping of special characters transparently.Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 295–297why, one step back2954. The generated paths are always absolute, avoiding unexpected behavior296 of relative paths in browsers.2975. If your application is placed outside the URL root, for example, inMerge pull request #3101 from tbm/docs-formattingDavid Lordbefore adoptionc795adf
lines 298–299why, one step back298 ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly299 handles that for you.Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 300–303why, one step back300301For example, here we use the :meth:`~flask.Flask.test_request_context` method302to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context`303tells Flask to behave as though it's handling a request even while we use asplit code and outputDavid Lordbefore adoption0b7a74d
line 304why, one step back304Python shell. See :ref:`context-locals`.Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
line 305why, one step back305split code and outputDavid Lordbefore adoption0b7a74d
lines 306–307why, one step back306.. code-block:: python307Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 308why, one step back308 from flask import url_forMerge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 309–319why, one step back309310 @app.route('/')311 def index():312 return 'index'313314 @app.route('/login')315 def login():316 return 'login'317318 @app.route('/user/<username>')319 def profile(username):Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 320why, one step back320 return f'{username}\'s profile'Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 321–327why, one step back321322 with app.test_request_context():323 print(url_for('index'))324 print(url_for('login'))325 print(url_for('login', next='/'))326 print(url_for('profile', username='John Doe'))327split code and outputDavid Lordbefore adoption0b7a74d
lines 328–334why, one step back328.. code-block:: text329330 /331 /login332 /login?next=/333 /user/John%20Doe334Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 335–344why, one step back335336HTTP Methods337````````````338339Web applications use different HTTP methods when accessing URLs. You should340familiarize yourself with the HTTP methods as you work with Flask. By default,341a route only answers to ``GET`` requests. You can use the ``methods`` argument342of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods.343::344Merge branch '1.0-maintenance'David Lordbefore adoption1fa9185
lines 345–346why, one step back345 from flask import request346Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 347–354why, one step back347 @app.route('/login', methods=['GET', 'POST'])348 def login():349 if request.method == 'POST':350 return do_the_login()351 else:352 return show_the_login_form()353354If ``GET`` is present, Flask automatically adds support for the ``HEAD`` methodMerge branch '1.0-maintenance'David Lordbefore adoption1fa9185
line 355why, one step back355and handles ``HEAD`` requests according to the `HTTP RFC`_. Likewise,Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 356–380why, one step back356``OPTIONS`` is automatically implemented for you.357358.. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt359360Static Files361------------362363Dynamic web applications also need static files. That's usually where364the CSS and JavaScript files are coming from. Ideally your web server is365configured to serve them for you, but during development Flask can do that366as well. Just create a folder called :file:`static` in your package or next to367your module and it will be available at ``/static`` on the application.368369To generate URLs for static files, use the special ``'static'`` endpoint name::370371 url_for('static', filename='style.css')372373The file has to be stored on the filesystem as :file:`static/style.css`.374375Rendering Templates376-------------------377378Generating HTML from within Python is not fun, and actually pretty379cumbersome because you have to do the HTML escaping on your own to keep380the application secure. Because of that Flask configures the `Jinja2Merge pull request #3427 from greyli/update-old-linksDavid Lordbefore adoption25a5d30
line 381why, one step back381<https://palletsprojects.com/p/jinja/>`_ template engine for you automatically.Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 382–413why, one step back382383To render a template you can use the :func:`~flask.render_template`384method. All you have to do is provide the name of the template and the385variables you want to pass to the template engine as keyword arguments.386Here's a simple example of how to render a template::387388 from flask import render_template389390 @app.route('/hello/')391 @app.route('/hello/<name>')392 def hello(name=None):393 return render_template('hello.html', name=name)394395Flask will look for templates in the :file:`templates` folder. So if your396application is a module, this folder is next to that module, if it's a397package it's actually inside your package:398399**Case 1**: a module::400401 /application.py402 /templates403 /hello.html404405**Case 2**: a package::406407 /application408 /__init__.py409 /templates410 /hello.html411412For templates you can use the full power of Jinja2 templates. Head over413to the official `Jinja2 Template DocumentationMerge pull request #3427 from greyli/update-old-linksDavid Lordbefore adoption25a5d30
line 414why, one step back414<https://jinja.palletsprojects.com/templates/>`_ for more information.Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 415–432why, one step back415416Here is an example template:417418.. sourcecode:: html+jinja419420 <!doctype html>421 <title>Hello from Flask</title>422 {% if name %}423 <h1>Hello {{ name }}!</h1>424 {% else %}425 <h1>Hello, World!</h1>426 {% endif %}427428Inside templates you also have access to the :class:`~flask.request`,429:class:`~flask.session` and :class:`~flask.g` [#]_ objects430as well as the :func:`~flask.get_flashed_messages` function.431432Templates are especially useful if inheritance is used. If you want toremove unused ref directivesDavid Lordbefore adoption171aabc
lines 433–435why, one step back433know how that works, see :doc:`patterns/templateinheritance`. Basically434template inheritance makes it possible to keep certain elements on each435page (like header, navigation and footer).Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 436–440why, one step back436437Automatic escaping is enabled, so if ``name`` contains HTML it will be escaped438automatically. If you can trust a variable and you know that it will be439safe HTML (for example because it came from a module that converts wiki440markup to HTML) you can mark it as safe by using theMerge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 441why, one step back441:class:`~markupsafe.Markup` class or by using the ``|safe`` filter in theMerge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 442–443why, one step back442template. Head over to the Jinja 2 documentation for more examples.443Merge remote-tracking branch 'origin/1.1.x'David Lordbefore adoption07556da
line 444why, one step back444Here is a basic introduction to how the :class:`~markupsafe.Markup` class works::Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
line 445why, one step back445Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 446why, one step back446 >>> from markupsafe import MarkupMerge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
line 447why, one step back447 >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374
line 448why, one step back448 Markup('<strong>Hello <blink>hacker</blink>!</strong>')Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
line 449why, one step back449 >>> Markup.escape('<blink>hacker</blink>')Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374
line 450why, one step back450 Markup('<blink>hacker</blink>')Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
line 451why, one step back451 >>> Markup('<em>Marked up</em> » HTML').striptags()Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374
line 452why, one step back452 'Marked up \xbb HTML'Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 453–461why, one step back453454.. versionchanged:: 0.5455456 Autoescaping is no longer enabled for all templates. The following457 extensions for templates trigger autoescaping: ``.html``, ``.htm``,458 ``.xml``, ``.xhtml``. Templates loaded from a string will have459 autoescaping disabled.460461.. [#] Unsure what that :class:`~flask.g` object is? It's something in whichremove unused ref directivesDavid Lordbefore adoption171aabc
lines 462–463why, one step back462 you can store information for your own needs. See the documentation463 for :class:`flask.g` and :doc:`patterns/sqlite3`.Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 464–581why, one step back464465466Accessing Request Data467----------------------468469For web applications it's crucial to react to the data a client sends to470the server. In Flask this information is provided by the global471:class:`~flask.request` object. If you have some experience with Python472you might be wondering how that object can be global and how Flask473manages to still be threadsafe. The answer is context locals:474475476.. _context-locals:477478Context Locals479``````````````480481.. admonition:: Insider Information482483 If you want to understand how that works and how you can implement484 tests with context locals, read this section, otherwise just skip it.485486Certain objects in Flask are global objects, but not of the usual kind.487These objects are actually proxies to objects that are local to a specific488context. What a mouthful. But that is actually quite easy to understand.489490Imagine the context being the handling thread. A request comes in and the491web server decides to spawn a new thread (or something else, the492underlying object is capable of dealing with concurrency systems other493than threads). When Flask starts its internal request handling it494figures out that the current thread is the active context and binds the495current application and the WSGI environments to that context (thread).496It does that in an intelligent way so that one application can invoke another497application without breaking.498499So what does this mean to you? Basically you can completely ignore that500this is the case unless you are doing something like unit testing. You501will notice that code which depends on a request object will suddenly break502because there is no request object. The solution is creating a request503object yourself and binding it to the context. The easiest solution for504unit testing is to use the :meth:`~flask.Flask.test_request_context`505context manager. In combination with the ``with`` statement it will bind a506test request so that you can interact with it. Here is an example::507508 from flask import request509510 with app.test_request_context('/hello', method='POST'):511 # now you can do something with the request until the512 # end of the with block, such as basic assertions:513 assert request.path == '/hello'514 assert request.method == 'POST'515516The other possibility is passing a whole WSGI environment to the517:meth:`~flask.Flask.request_context` method::518519 with app.request_context(environ):520 assert request.method == 'POST'521522The Request Object523``````````````````524525The request object is documented in the API section and we will not cover526it here in detail (see :class:`~flask.Request`). Here is a broad overview of527some of the most common operations. First of all you have to import it from528the ``flask`` module::529530 from flask import request531532The current request method is available by using the533:attr:`~flask.Request.method` attribute. To access form data (data534transmitted in a ``POST`` or ``PUT`` request) you can use the535:attr:`~flask.Request.form` attribute. Here is a full example of the two536attributes mentioned above::537538 @app.route('/login', methods=['POST', 'GET'])539 def login():540 error = None541 if request.method == 'POST':542 if valid_login(request.form['username'],543 request.form['password']):544 return log_the_user_in(request.form['username'])545 else:546 error = 'Invalid username/password'547 # the code below is executed if the request method548 # was GET or the credentials were invalid549 return render_template('login.html', error=error)550551What happens if the key does not exist in the ``form`` attribute? In that552case a special :exc:`KeyError` is raised. You can catch it like a553standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request554error page is shown instead. So for many situations you don't have to555deal with that problem.556557To access parameters submitted in the URL (``?key=value``) you can use the558:attr:`~flask.Request.args` attribute::559560 searchword = request.args.get('key', '')561562We recommend accessing URL parameters with `get` or by catching the563:exc:`KeyError` because users might change the URL and presenting them a 400564bad request page in that case is not user friendly.565566For a full list of methods and attributes of the request object, head over567to the :class:`~flask.Request` documentation.568569570File Uploads571````````````572573You can handle uploaded files with Flask easily. Just make sure not to574forget to set the ``enctype="multipart/form-data"`` attribute on your HTML575form, otherwise the browser will not transmit your files at all.576577Uploaded files are stored in memory or at a temporary location on the578filesystem. You can access those files by looking at the579:attr:`~flask.request.files` attribute on the request object. Each580uploaded file is stored in that dictionary. It behaves just like a581standard Python :class:`file` object, but it also has aMerge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
lines 582–584why, one step back582:meth:`~werkzeug.datastructures.FileStorage.save` method that583allows you to store that file on the filesystem of the server.584Here is a simple example showing how that works::Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 585–596why, one step back585586 from flask import request587588 @app.route('/upload', methods=['GET', 'POST'])589 def upload_file():590 if request.method == 'POST':591 f = request.files['the_file']592 f.save('/var/www/uploads/uploaded_file.txt')593 ...594595If you want to know how the file was named on the client before it was596uploaded to your application, you can access theMerge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
lines 597–601why, one step back597:attr:`~werkzeug.datastructures.FileStorage.filename` attribute.598However please keep in mind that this value can be forged599so never ever trust that value. If you want to use the filename600of the client to store the file on the server, pass it through the601:func:`~werkzeug.utils.secure_filename` function thatMerge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 602–608why, one step back602Werkzeug provides for you::603604 from werkzeug.utils import secure_filename605606 @app.route('/upload', methods=['GET', 'POST'])607 def upload_file():608 if request.method == 'POST':Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374
lines 609–610why, one step back609 file = request.files['the_file']610 file.save(f"/var/www/uploads/{secure_filename(f.filename)}")Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 611–612why, one step back611 ...612remove unused ref directivesDavid Lordbefore adoption171aabc
line 613why, one step back613For some better examples, see :doc:`patterns/fileuploads`.Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 614–652why, one step back614615Cookies616```````617618To access cookies you can use the :attr:`~flask.Request.cookies`619attribute. To set cookies you can use the620:attr:`~flask.Response.set_cookie` method of response objects. The621:attr:`~flask.Request.cookies` attribute of request objects is a622dictionary with all the cookies the client transmits. If you want to use623sessions, do not use the cookies directly but instead use the624:ref:`sessions` in Flask that add some security on top of cookies for you.625626Reading cookies::627628 from flask import request629630 @app.route('/')631 def index():632 username = request.cookies.get('username')633 # use cookies.get(key) instead of cookies[key] to not get a634 # KeyError if the cookie is missing.635636Storing cookies::637638 from flask import make_response639640 @app.route('/')641 def index():642 resp = make_response(render_template(...))643 resp.set_cookie('username', 'the username')644 return resp645646Note that cookies are set on response objects. Since you normally647just return strings from the view functions Flask will convert them into648response objects for you. If you explicitly want to do that you can use649the :meth:`~flask.make_response` function and then modify it.650651Sometimes you might want to set a cookie at a point where the response652object does not exist yet. This is possible by utilizing theremove unused ref directivesDavid Lordbefore adoption171aabc
line 653why, one step back653:doc:`patterns/deferredcallbacks` pattern.Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 654–692why, one step back654655For this also see :ref:`about-responses`.656657Redirects and Errors658--------------------659660To redirect a user to another endpoint, use the :func:`~flask.redirect`661function; to abort a request early with an error code, use the662:func:`~flask.abort` function::663664 from flask import abort, redirect, url_for665666 @app.route('/')667 def index():668 return redirect(url_for('login'))669670 @app.route('/login')671 def login():672 abort(401)673 this_is_never_executed()674675This is a rather pointless example because a user will be redirected from676the index to a page they cannot access (401 means access denied) but it677shows how that works.678679By default a black and white error page is shown for each error code. If680you want to customize the error page, you can use the681:meth:`~flask.Flask.errorhandler` decorator::682683 from flask import render_template684685 @app.errorhandler(404)686 def page_not_found(error):687 return render_template('page_not_found.html'), 404688689Note the ``404`` after the :func:`~flask.render_template` call. This690tells Flask that the status code of that page should be 404 which means691not found. By default 200 is assumed which translates to: all went well.692remove unused ref directivesDavid Lordbefore adoption171aabc
line 693why, one step back693See :doc:`errorhandling` for more details.Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 694–699why, one step back694695.. _about-responses:696697About Responses698---------------699Merge pull request #3111 from pgjones/masterDavid Lordbefore adoption855d59b
lines 700–706why, one step back700The return value from a view function is automatically converted into701a response object for you. If the return value is a string it's702converted into a response object with the string as response body, a703``200 OK`` status code and a :mimetype:`text/html` mimetype. If the704return value is a dict, :func:`jsonify` is called to produce a response.705The logic that Flask applies to converting return values into response706objects is as follows:Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 707–709why, one step back7077081. If a response object of the correct type is returned it's directly709 returned from the view.Merge pull request #3111 from pgjones/masterDavid Lordbefore adoption855d59b
lines 710–719why, one step back7102. If it's a string, a response object is created with that data and711 the default parameters.7123. If it's a dict, a response object is created using ``jsonify``.7134. If a tuple is returned the items in the tuple can provide extra714 information. Such tuples have to be in the form715 ``(response, status)``, ``(response, headers)``, or716 ``(response, status, headers)``. The ``status`` value will override717 the status code and ``headers`` can be a list or dictionary of718 additional header values.7195. If none of that works, Flask will assume the return value is aMerge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 720–726why, one step back720 valid WSGI application and convert that into a response object.721722If you want to get hold of the resulting response object inside the view723you can use the :func:`~flask.make_response` function.724725Imagine you have a view like this::726Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
lines 727–728why, one step back727 from flask import render_template728Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 729–736why, one step back729 @app.errorhandler(404)730 def not_found(error):731 return render_template('error.html'), 404732733You just need to wrap the return expression with734:func:`~flask.make_response` and get the response object to modify it, then735return it::736Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
lines 737–738why, one step back737 from flask import make_response738Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 739–743why, one step back739 @app.errorhandler(404)740 def not_found(error):741 resp = make_response(render_template('error.html'), 404)742 resp.headers['X-Something'] = 'A value'743 return respMerge pull request #3111 from pgjones/masterDavid Lordbefore adoption855d59b
lines 744–771why, one step back744745746APIs with JSON747``````````````748749A common response format when writing an API is JSON. It's easy to get750started writing such an API with Flask. If you return a ``dict`` from a751view, it will be converted to a JSON response.752753.. code-block:: python754755 @app.route("/me")756 def me_api():757 user = get_current_user()758 return {759 "username": user.username,760 "theme": user.theme,761 "image": url_for("user_image", filename=user.image),762 }763764Depending on your API design, you may want to create JSON responses for765types other than ``dict``. In that case, use the766:func:`~flask.json.jsonify` function, which will serialize any supported767JSON data type. Or look into Flask community extensions that support768more complex applications.769770.. code-block:: python771Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
lines 772–773why, one step back772 from flask import jsonify773Merge pull request #3111 from pgjones/masterDavid Lordbefore adoption855d59b
lines 774–778why, one step back774 @app.route("/users")775 def users_api():776 users = get_all_users()777 return jsonify([user.to_json() for user in users])778Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 779–794why, one step back779780.. _sessions:781782Sessions783--------784785In addition to the request object there is also a second object called786:class:`~flask.session` which allows you to store information specific to a787user from one request to the next. This is implemented on top of cookies788for you and signs the cookies cryptographically. What this means is that789the user could look at the contents of your cookie but not modify it,790unless they know the secret key used for signing.791792In order to use sessions you have to set a secret key. Here is how793sessions work::794Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 795why, one step back795 from flask import sessionMerge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 796–802why, one step back796797 # Set the secret key to some random bytes. Keep this really secret!798 app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'799800 @app.route('/')801 def index():802 if 'username' in session:Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 803why, one step back803 return f'Logged in as {session["username"]}'Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 804–856why, one step back804 return 'You are not logged in'805806 @app.route('/login', methods=['GET', 'POST'])807 def login():808 if request.method == 'POST':809 session['username'] = request.form['username']810 return redirect(url_for('index'))811 return '''812 <form method="post">813 <p><input type=text name=username>814 <p><input type=submit value=Login>815 </form>816 '''817818 @app.route('/logout')819 def logout():820 # remove the username from the session if it's there821 session.pop('username', None)822 return redirect(url_for('index'))823824.. admonition:: How to generate good secret keys825826 A secret key should be as random as possible. Your operating system has827 ways to generate pretty random data based on a cryptographic random828 generator. Use the following command to quickly generate a value for829 :attr:`Flask.secret_key` (or :data:`SECRET_KEY`)::830831 $ python -c 'import os; print(os.urandom(16))'832 b'_5#y2L"F4Q8z\n\xec]/'833834A note on cookie-based sessions: Flask will take the values you put into the835session object and serialize them into a cookie. If you are finding some836values do not persist across requests, cookies are indeed enabled, and you are837not getting a clear error message, check the size of the cookie in your page838responses compared to the size supported by web browsers.839840Besides the default client-side based sessions, if you want to handle841sessions on the server-side instead, there are several842Flask extensions that support this.843844Message Flashing845----------------846847Good applications and user interfaces are all about feedback. If the user848does not get enough feedback they will probably end up hating the849application. Flask provides a really simple way to give feedback to a850user with the flashing system. The flashing system basically makes it851possible to record a message at the end of a request and access it on the next852(and only the next) request. This is usually combined with a layout853template to expose the message.854855To flash a message use the :func:`~flask.flash` method, to get hold of the856messages you can use :func:`~flask.get_flashed_messages` which is alsoremove unused ref directivesDavid Lordbefore adoption171aabc
lines 857–858why, one step back857available in the templates. See :doc:`patterns/flashing` for a full858example.Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 859–865why, one step back859860Logging861-------862863.. versionadded:: 0.3864865Sometimes you might be in a situation where you deal with data thatMerge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
lines 866–871why, one step back866should be correct, but actually is not. For example you may have867some client-side code that sends an HTTP request to the server868but it's obviously malformed. This might be caused by a user tampering869with the data, or the client code failing. Most of the time it's okay870to reply with ``400 Bad Request`` in that situation, but sometimes871that won't do and the code has to continue working.Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 872–883why, one step back872873You may still want to log that something fishy happened. This is where874loggers come in handy. As of Flask 0.3 a logger is preconfigured for you875to use.876877Here are some example log calls::878879 app.logger.debug('A value for debugging')880 app.logger.warning('A warning occurred (%d apples)', 42)881 app.logger.error('An error occurred')882883The attached :attr:`~flask.Flask.logger` is a standard loggingMerge branch '1.0.x'David Lordbefore adoption1351d0a
lines 884–885why, one step back884:class:`~logging.Logger`, so head over to the official :mod:`logging`885docs for more information.Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
line 886why, one step back886remove unused ref directivesDavid Lordbefore adoption171aabc
line 887why, one step back887See :doc:`errorhandling`.Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
line 888why, one step back888remove unused ref directivesDavid Lordbefore adoption171aabc
line 889why, one step back889Merge branch '1.1.x'David Lordbefore adoption40eadfc
lines 890–891why, one step back890Hooking in WSGI Middleware891--------------------------Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
line 892why, one step back892Merge branch '1.1.x'David Lordbefore adoption40eadfc
lines 893–896why, one step back893To add WSGI middleware to your Flask application, wrap the application's894``wsgi_app`` attribute. For example, to apply Werkzeug's895:class:`~werkzeug.middlware.proxy_fix.ProxyFix` middleware for running896behind Nginx:Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
line 897why, one step back897Merge branch '1.1.x'David Lordbefore adoption40eadfc
lines 898–905why, one step back898.. code-block:: python899900 from werkzeug.middleware.proxy_fix import ProxyFix901 app.wsgi_app = ProxyFix(app.wsgi_app)902903Wrapping ``app.wsgi_app`` instead of ``app`` means that ``app`` still904points at your Flask application, not at the middleware, so you can905continue to use and configure ``app`` directly.Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 906–913why, one step back906907Using Flask Extensions908----------------------909910Extensions are packages that help you accomplish common tasks. For911example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple912and easy to use with Flask.913remove unused ref directivesDavid Lordbefore adoption171aabc
line 914why, one step back914For more on Flask extensions, see :doc:`extensions`.Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 915–918why, one step back915916Deploying to a Web Server917-------------------------918remove unused ref directivesDavid Lordbefore adoption171aabc
line 919why, one step back919Ready to deploy your new Flask app? See :doc:`deploying/index`.