quickstart.rst
This file
Path
docs/quickstart.rst
938 lines · 31.9 KiB
Last changed by
Merge branch '2.0.x'David Lordbefore adoptionea66c68
History of this fileTake it
The walk stopped after 200 commits: lines older than 295e1e7 point at it.
add EditorConfigDavid Lordbefore adoption295e1e7
lines 1–46why, one step back1Quickstart2==========34Eager to get started? This page gives a good introduction to Flask.5Follow :doc:`installation` to set up a project and install Flask first.678A Minimal Application9---------------------1011A minimal Flask application looks something like this:1213.. code-block:: python1415 from flask import Flask1617 app = Flask(__name__)1819 @app.route("/")20 def hello_world():21 return "<p>Hello, World!</p>"2223So what did that code do?24251. 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.3738Save it as :file:`hello.py` or something similar. Make sure to not call39your application :file:`flask.py` because this would conflict with Flask40itself.4142To run the application, use the :command:`flask` command or43:command:`python -m flask`. Before you can do that you need44to tell your terminal the application to work with by exporting the45``FLASK_APP`` environment variable:46Add command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc
line 47why, one step back47.. tabs::add EditorConfigDavid Lordbefore adoption295e1e7
line 48why, one step back48Add command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc
line 49why, one step back49 .. group-tab:: Bashadd EditorConfigDavid Lordbefore adoption295e1e7
line 50why, one step back50Add command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc
line 51why, one step back51 .. code-block:: textadd EditorConfigDavid Lordbefore adoption295e1e7
line 52why, one step back52Merge pull request #3999 from greyli/improve-cli-docsDavid Lordbefore adoption28262c3
line 53why, one step back53 $ export FLASK_APP=helloAdd command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc
lines 54–55why, one step back54 $ flask run55 * Running on http://127.0.0.1:5000/add EditorConfigDavid Lordbefore adoption295e1e7
line 56why, one step back56Add command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc
line 57why, one step back57 .. group-tab:: CMDadd EditorConfigDavid Lordbefore adoption295e1e7
line 58why, one step back58Add command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc
line 59why, one step back59 .. code-block:: textadd EditorConfigDavid Lordbefore adoption295e1e7
line 60why, one step back60Merge pull request #3999 from greyli/improve-cli-docsDavid Lordbefore adoption28262c3
line 61why, one step back61 > set FLASK_APP=helloAdd command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc
lines 62–68why, one step back62 > flask run63 * Running on http://127.0.0.1:5000/6465 .. group-tab:: Powershell6667 .. code-block:: text68Merge pull request #3999 from greyli/improve-cli-docsDavid Lordbefore adoption28262c3
line 69why, one step back69 > $env:FLASK_APP = "hello"Add command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc
lines 70–71why, one step back70 > flask run71 * Running on http://127.0.0.1:5000/Merge pull request #3999 from greyli/improve-cli-docsDavid Lordbefore adoption28262c3
lines 72–77why, one step back7273.. admonition:: Application Discovery Behavior7475 As a shortcut, if the file is named ``app.py`` or ``wsgi.py``, you76 don't have to set the ``FLASK_APP`` environment variable. See77 :doc:`/cli` for more details.Add command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc
line 78why, one step back78add EditorConfigDavid Lordbefore adoption295e1e7
lines 79–113why, one step back79This launches a very simple builtin server, which is good enough for80testing but probably not what you want to use in production. For81deployment options see :doc:`deploying/index`.8283Now head over to http://127.0.0.1:5000/, and you should see your hello84world greeting.8586.. _public-server:8788.. admonition:: Externally Visible Server8990 If you run the server you will notice that the server is only accessible91 from your own computer, not from any other in the network. This is the92 default because in debugging mode a user of the application can execute93 arbitrary Python code on your computer.9495 If you have the debugger disabled or trust the users on your network,96 you can make the server publicly available simply by adding97 ``--host=0.0.0.0`` to the command line::9899 $ flask run --host=0.0.0.0100101 This tells your operating system to listen on all public IPs.102103104What to do if the Server does not Start105---------------------------------------106107In case the :command:`python -m flask` fails or :command:`flask`108does not exist, there are multiple reasons this might be the case.109First of all you need to look at the error message.110111Old Version of Flask112````````````````````113Merge branch '1.1.x'David Lordbefore adoption15a49e7
line 114why, one step back114Versions of Flask older than 0.11 used to have different ways to start theadd EditorConfigDavid Lordbefore adoption295e1e7
lines 115–134why, one step back115application. In short, the :command:`flask` command did not exist, and116neither did :command:`python -m flask`. In that case you have two options:117either upgrade to newer Flask versions or have a look at :doc:`/server`118to see the alternative method for running a server.119120Invalid Import Name121```````````````````122123The ``FLASK_APP`` environment variable is the name of the module to import at124:command:`flask run`. In case that module is incorrectly named you will get an125import error upon start (or if debug is enabled when you navigate to the126application). It will tell you what it tried to import and why it failed.127128The most common reason is a typo or because you did not actually create an129``app`` object.130131132Debug Mode133----------134Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 135–138why, one step back135The ``flask run`` command can do more than just start the development136server. By enabling debug mode, the server will automatically reload if137code changes, and will show an interactive debugger in the browser if an138error occurs during a request.add EditorConfigDavid Lordbefore adoption295e1e7
line 139why, one step back139Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 140–143why, one step back140.. image:: _static/debugger.png141 :align: center142 :class: screenshot143 :alt: The interactive debugger in action.add EditorConfigDavid Lordbefore adoption295e1e7
line 144why, one step back144Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
line 145why, one step back145.. warning::add EditorConfigDavid Lordbefore adoption295e1e7
line 146why, one step back146Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 147–150why, one step back147 The debugger allows executing arbitrary Python code from the148 browser. It is protected by a pin, but still represents a major149 security risk. Do not run the development server or debugger in a150 production environment.add EditorConfigDavid Lordbefore adoption295e1e7
line 151why, one step back151Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 152–153why, one step back152To enable all development features, set the ``FLASK_ENV`` environment153variable to ``development`` before calling ``flask run``.add EditorConfigDavid Lordbefore adoption295e1e7
line 154why, one step back154Add command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc
line 155why, one step back155.. tabs::add EditorConfigDavid Lordbefore adoption295e1e7
line 156why, one step back156Add command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc
lines 157–176why, one step back157 .. group-tab:: Bash158159 .. code-block:: text160161 $ export FLASK_ENV=development162 $ flask run163164 .. group-tab:: CMD165166 .. code-block:: text167168 > set FLASK_ENV=development169 > flask run170171 .. group-tab:: Powershell172173 .. code-block:: text174175 > $env:FLASK_ENV = "development"176 > flask runadd EditorConfigDavid Lordbefore adoption295e1e7
line 177why, one step back177Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
line 178why, one step back178See also:add EditorConfigDavid Lordbefore adoption295e1e7
line 179why, one step back179Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 180–185why, one step back180- :doc:`/server` and :doc:`/cli` for information about running in181 development mode.182- :doc:`/debugging` for information about using the built-in debugger183 and other debuggers.184- :doc:`/logging` and :doc:`/errorhandling` to log errors and display185 nice error pages.add EditorConfigDavid Lordbefore adoption295e1e7
lines 186–248why, one step back186187188HTML Escaping189-------------190191When returning HTML (the default response type in Flask), any192user-provided values rendered in the output must be escaped to protect193from injection attacks. HTML templates rendered with Jinja, introduced194later, will do this automatically.195196:func:`~markupsafe.escape`, shown here, can be used manually. It is197omitted in most examples for brevity, but you should always be aware of198how you're using untrusted data.199200.. code-block:: python201202 from markupsafe import escape203204 @app.route("/<name>")205 def hello(name):206 return f"Hello, {escape(name)}!"207208If a user managed to submit the name ``<script>alert("bad")</script>``,209escaping causes it to be rendered as text, rather than running the210script in the user's browser.211212``<name>`` in the route captures a value from the URL and passes it to213the view function. These variable rules are explained below.214215216Routing217-------218219Modern web applications use meaningful URLs to help users. Users are more220likely to like a page and come back if the page uses a meaningful URL they can221remember and use to directly visit a page.222223Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. ::224225 @app.route('/')226 def index():227 return 'Index Page'228229 @app.route('/hello')230 def hello():231 return 'Hello, World'232233You can do more! You can make parts of the URL dynamic and attach multiple234rules to a function.235236Variable Rules237``````````````238239You can add variable sections to a URL by marking sections with240``<variable_name>``. Your function then receives the ``<variable_name>``241as a keyword argument. Optionally, you can use a converter to specify the type242of the argument like ``<converter:variable_name>``. ::243244 from markupsafe import escape245246 @app.route('/user/<username>')247 def show_user_profile(username):248 # show the user profile for that userMerge branch '2.0.x'David Lordbefore adoption83f7efa
line 249why, one step back249 return f'User {escape(username)}'add EditorConfigDavid Lordbefore adoption295e1e7
lines 250–258why, one step back250251 @app.route('/post/<int:post_id>')252 def show_post(post_id):253 # show the post with the given id, the id is an integer254 return f'Post {post_id}'255256 @app.route('/path/<path:subpath>')257 def show_subpath(subpath):258 # show the subpath after /path/Merge branch '2.0.x'David Lordbefore adoption83f7efa
line 259why, one step back259 return f'Subpath {escape(subpath)}'add EditorConfigDavid Lordbefore adoption295e1e7
lines 260–286why, one step back260261Converter types:262263========== ==========================================264``string`` (default) accepts any text without a slash265``int`` accepts positive integers266``float`` accepts positive floating point values267``path`` like ``string`` but also accepts slashes268``uuid`` accepts UUID strings269========== ==========================================270271272Unique URLs / Redirection Behavior273``````````````````````````````````274275The following two rules differ in their use of a trailing slash. ::276277 @app.route('/projects/')278 def projects():279 return 'The project page'280281 @app.route('/about')282 def about():283 return 'The about page'284285The canonical URL for the ``projects`` endpoint has a trailing slash.286It's similar to a folder in a file system. If you access the URL withoutMerge pull request #3674 from DeepOde/masterGrey Libefore adoption3fe5eec
lines 287–288why, one step back287a trailing slash (``/projects``), Flask redirects you to the canonical URL288with the trailing slash (``/projects/``).add EditorConfigDavid Lordbefore adoption295e1e7
lines 289–291why, one step back289290The canonical URL for the ``about`` endpoint does not have a trailing291slash. It's similar to the pathname of a file. Accessing the URL with aMerge pull request #3674 from DeepOde/masterGrey Libefore adoption3fe5eec
lines 292–294why, one step back292trailing slash (``/about/``) produces a 404 "Not Found" error. This helps293keep URLs unique for these resources, which helps search engines avoid294indexing the same page twice.add EditorConfigDavid Lordbefore adoption295e1e7
lines 295–446why, one step back295296297.. _url-building:298299URL Building300````````````301302To build a URL to a specific function, use the :func:`~flask.url_for` function.303It accepts the name of the function as its first argument and any number of304keyword arguments, each corresponding to a variable part of the URL rule.305Unknown variable parts are appended to the URL as query parameters.306307Why would you want to build URLs using the URL reversing function308:func:`~flask.url_for` instead of hard-coding them into your templates?3093101. Reversing is often more descriptive than hard-coding the URLs.3112. You can change your URLs in one go instead of needing to remember to312 manually change hard-coded URLs.3133. URL building handles escaping of special characters transparently.3144. The generated paths are always absolute, avoiding unexpected behavior315 of relative paths in browsers.3165. If your application is placed outside the URL root, for example, in317 ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly318 handles that for you.319320For example, here we use the :meth:`~flask.Flask.test_request_context` method321to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context`322tells Flask to behave as though it's handling a request even while we use a323Python shell. See :ref:`context-locals`.324325.. code-block:: python326327 from flask import url_for328329 @app.route('/')330 def index():331 return 'index'332333 @app.route('/login')334 def login():335 return 'login'336337 @app.route('/user/<username>')338 def profile(username):339 return f'{username}\'s profile'340341 with app.test_request_context():342 print(url_for('index'))343 print(url_for('login'))344 print(url_for('login', next='/'))345 print(url_for('profile', username='John Doe'))346347.. code-block:: text348349 /350 /login351 /login?next=/352 /user/John%20Doe353354355HTTP Methods356````````````357358Web applications use different HTTP methods when accessing URLs. You should359familiarize yourself with the HTTP methods as you work with Flask. By default,360a route only answers to ``GET`` requests. You can use the ``methods`` argument361of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods.362::363364 from flask import request365366 @app.route('/login', methods=['GET', 'POST'])367 def login():368 if request.method == 'POST':369 return do_the_login()370 else:371 return show_the_login_form()372373If ``GET`` is present, Flask automatically adds support for the ``HEAD`` method374and handles ``HEAD`` requests according to the `HTTP RFC`_. Likewise,375``OPTIONS`` is automatically implemented for you.376377.. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt378379Static Files380------------381382Dynamic web applications also need static files. That's usually where383the CSS and JavaScript files are coming from. Ideally your web server is384configured to serve them for you, but during development Flask can do that385as well. Just create a folder called :file:`static` in your package or next to386your module and it will be available at ``/static`` on the application.387388To generate URLs for static files, use the special ``'static'`` endpoint name::389390 url_for('static', filename='style.css')391392The file has to be stored on the filesystem as :file:`static/style.css`.393394Rendering Templates395-------------------396397Generating HTML from within Python is not fun, and actually pretty398cumbersome because you have to do the HTML escaping on your own to keep399the application secure. Because of that Flask configures the `Jinja2400<https://palletsprojects.com/p/jinja/>`_ template engine for you automatically.401402To render a template you can use the :func:`~flask.render_template`403method. All you have to do is provide the name of the template and the404variables you want to pass to the template engine as keyword arguments.405Here's a simple example of how to render a template::406407 from flask import render_template408409 @app.route('/hello/')410 @app.route('/hello/<name>')411 def hello(name=None):412 return render_template('hello.html', name=name)413414Flask will look for templates in the :file:`templates` folder. So if your415application is a module, this folder is next to that module, if it's a416package it's actually inside your package:417418**Case 1**: a module::419420 /application.py421 /templates422 /hello.html423424**Case 2**: a package::425426 /application427 /__init__.py428 /templates429 /hello.html430431For templates you can use the full power of Jinja2 templates. Head over432to the official `Jinja2 Template Documentation433<https://jinja.palletsprojects.com/templates/>`_ for more information.434435Here is an example template:436437.. sourcecode:: html+jinja438439 <!doctype html>440 <title>Hello from Flask</title>441 {% if name %}442 <h1>Hello {{ name }}!</h1>443 {% else %}444 <h1>Hello, World!</h1>445 {% endif %}446Merge remote-tracking branch 'origin/2.0.x' into mainGrey Libefore adoptionba6db2e
lines 447–449why, one step back447Inside templates you also have access to the :data:`~flask.Flask.config`,448:class:`~flask.request`, :class:`~flask.session` and :class:`~flask.g` [#]_ objects449as well as the :func:`~flask.url_for` and :func:`~flask.get_flashed_messages` functions.add EditorConfigDavid Lordbefore adoption295e1e7
lines 450–470why, one step back450451Templates are especially useful if inheritance is used. If you want to452know how that works, see :doc:`patterns/templateinheritance`. Basically453template inheritance makes it possible to keep certain elements on each454page (like header, navigation and footer).455456Automatic escaping is enabled, so if ``name`` contains HTML it will be escaped457automatically. If you can trust a variable and you know that it will be458safe HTML (for example because it came from a module that converts wiki459markup to HTML) you can mark it as safe by using the460:class:`~markupsafe.Markup` class or by using the ``|safe`` filter in the461template. Head over to the Jinja 2 documentation for more examples.462463Here is a basic introduction to how the :class:`~markupsafe.Markup` class works::464465 >>> from markupsafe import Markup466 >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'467 Markup('<strong>Hello <blink>hacker</blink>!</strong>')468 >>> Markup.escape('<blink>hacker</blink>')469 Markup('<blink>hacker</blink>')470 >>> Markup('<em>Marked up</em> » HTML').striptags()Merge branch '2.0.x'David Lordbefore adoptionea66c68
line 471why, one step back471 'Marked up » HTML'add EditorConfigDavid Lordbefore adoption295e1e7
lines 472–628why, one step back472473.. versionchanged:: 0.5474475 Autoescaping is no longer enabled for all templates. The following476 extensions for templates trigger autoescaping: ``.html``, ``.htm``,477 ``.xml``, ``.xhtml``. Templates loaded from a string will have478 autoescaping disabled.479480.. [#] Unsure what that :class:`~flask.g` object is? It's something in which481 you can store information for your own needs. See the documentation482 for :class:`flask.g` and :doc:`patterns/sqlite3`.483484485Accessing Request Data486----------------------487488For web applications it's crucial to react to the data a client sends to489the server. In Flask this information is provided by the global490:class:`~flask.request` object. If you have some experience with Python491you might be wondering how that object can be global and how Flask492manages to still be threadsafe. The answer is context locals:493494495.. _context-locals:496497Context Locals498``````````````499500.. admonition:: Insider Information501502 If you want to understand how that works and how you can implement503 tests with context locals, read this section, otherwise just skip it.504505Certain objects in Flask are global objects, but not of the usual kind.506These objects are actually proxies to objects that are local to a specific507context. What a mouthful. But that is actually quite easy to understand.508509Imagine the context being the handling thread. A request comes in and the510web server decides to spawn a new thread (or something else, the511underlying object is capable of dealing with concurrency systems other512than threads). When Flask starts its internal request handling it513figures out that the current thread is the active context and binds the514current application and the WSGI environments to that context (thread).515It does that in an intelligent way so that one application can invoke another516application without breaking.517518So what does this mean to you? Basically you can completely ignore that519this is the case unless you are doing something like unit testing. You520will notice that code which depends on a request object will suddenly break521because there is no request object. The solution is creating a request522object yourself and binding it to the context. The easiest solution for523unit testing is to use the :meth:`~flask.Flask.test_request_context`524context manager. In combination with the ``with`` statement it will bind a525test request so that you can interact with it. Here is an example::526527 from flask import request528529 with app.test_request_context('/hello', method='POST'):530 # now you can do something with the request until the531 # end of the with block, such as basic assertions:532 assert request.path == '/hello'533 assert request.method == 'POST'534535The other possibility is passing a whole WSGI environment to the536:meth:`~flask.Flask.request_context` method::537538 with app.request_context(environ):539 assert request.method == 'POST'540541The Request Object542``````````````````543544The request object is documented in the API section and we will not cover545it here in detail (see :class:`~flask.Request`). Here is a broad overview of546some of the most common operations. First of all you have to import it from547the ``flask`` module::548549 from flask import request550551The current request method is available by using the552:attr:`~flask.Request.method` attribute. To access form data (data553transmitted in a ``POST`` or ``PUT`` request) you can use the554:attr:`~flask.Request.form` attribute. Here is a full example of the two555attributes mentioned above::556557 @app.route('/login', methods=['POST', 'GET'])558 def login():559 error = None560 if request.method == 'POST':561 if valid_login(request.form['username'],562 request.form['password']):563 return log_the_user_in(request.form['username'])564 else:565 error = 'Invalid username/password'566 # the code below is executed if the request method567 # was GET or the credentials were invalid568 return render_template('login.html', error=error)569570What happens if the key does not exist in the ``form`` attribute? In that571case a special :exc:`KeyError` is raised. You can catch it like a572standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request573error page is shown instead. So for many situations you don't have to574deal with that problem.575576To access parameters submitted in the URL (``?key=value``) you can use the577:attr:`~flask.Request.args` attribute::578579 searchword = request.args.get('key', '')580581We recommend accessing URL parameters with `get` or by catching the582:exc:`KeyError` because users might change the URL and presenting them a 400583bad request page in that case is not user friendly.584585For a full list of methods and attributes of the request object, head over586to the :class:`~flask.Request` documentation.587588589File Uploads590````````````591592You can handle uploaded files with Flask easily. Just make sure not to593forget to set the ``enctype="multipart/form-data"`` attribute on your HTML594form, otherwise the browser will not transmit your files at all.595596Uploaded files are stored in memory or at a temporary location on the597filesystem. You can access those files by looking at the598:attr:`~flask.request.files` attribute on the request object. Each599uploaded file is stored in that dictionary. It behaves just like a600standard Python :class:`file` object, but it also has a601:meth:`~werkzeug.datastructures.FileStorage.save` method that602allows you to store that file on the filesystem of the server.603Here is a simple example showing how that works::604605 from flask import request606607 @app.route('/upload', methods=['GET', 'POST'])608 def upload_file():609 if request.method == 'POST':610 f = request.files['the_file']611 f.save('/var/www/uploads/uploaded_file.txt')612 ...613614If you want to know how the file was named on the client before it was615uploaded to your application, you can access the616:attr:`~werkzeug.datastructures.FileStorage.filename` attribute.617However please keep in mind that this value can be forged618so never ever trust that value. If you want to use the filename619of the client to store the file on the server, pass it through the620:func:`~werkzeug.utils.secure_filename` function that621Werkzeug provides for you::622623 from werkzeug.utils import secure_filename624625 @app.route('/upload', methods=['GET', 'POST'])626 def upload_file():627 if request.method == 'POST':628 file = request.files['the_file']Merge remote-tracking branch 'origin/2.0.x'David Lordbefore adoptionafc13b9
line 629why, one step back629 file.save(f"/var/www/uploads/{secure_filename(file.filename)}")add EditorConfigDavid Lordbefore adoption295e1e7
lines 630–849why, one step back630 ...631632For some better examples, see :doc:`patterns/fileuploads`.633634Cookies635```````636637To access cookies you can use the :attr:`~flask.Request.cookies`638attribute. To set cookies you can use the639:attr:`~flask.Response.set_cookie` method of response objects. The640:attr:`~flask.Request.cookies` attribute of request objects is a641dictionary with all the cookies the client transmits. If you want to use642sessions, do not use the cookies directly but instead use the643:ref:`sessions` in Flask that add some security on top of cookies for you.644645Reading cookies::646647 from flask import request648649 @app.route('/')650 def index():651 username = request.cookies.get('username')652 # use cookies.get(key) instead of cookies[key] to not get a653 # KeyError if the cookie is missing.654655Storing cookies::656657 from flask import make_response658659 @app.route('/')660 def index():661 resp = make_response(render_template(...))662 resp.set_cookie('username', 'the username')663 return resp664665Note that cookies are set on response objects. Since you normally666just return strings from the view functions Flask will convert them into667response objects for you. If you explicitly want to do that you can use668the :meth:`~flask.make_response` function and then modify it.669670Sometimes you might want to set a cookie at a point where the response671object does not exist yet. This is possible by utilizing the672:doc:`patterns/deferredcallbacks` pattern.673674For this also see :ref:`about-responses`.675676Redirects and Errors677--------------------678679To redirect a user to another endpoint, use the :func:`~flask.redirect`680function; to abort a request early with an error code, use the681:func:`~flask.abort` function::682683 from flask import abort, redirect, url_for684685 @app.route('/')686 def index():687 return redirect(url_for('login'))688689 @app.route('/login')690 def login():691 abort(401)692 this_is_never_executed()693694This is a rather pointless example because a user will be redirected from695the index to a page they cannot access (401 means access denied) but it696shows how that works.697698By default a black and white error page is shown for each error code. If699you want to customize the error page, you can use the700:meth:`~flask.Flask.errorhandler` decorator::701702 from flask import render_template703704 @app.errorhandler(404)705 def page_not_found(error):706 return render_template('page_not_found.html'), 404707708Note the ``404`` after the :func:`~flask.render_template` call. This709tells Flask that the status code of that page should be 404 which means710not found. By default 200 is assumed which translates to: all went well.711712See :doc:`errorhandling` for more details.713714.. _about-responses:715716About Responses717---------------718719The return value from a view function is automatically converted into720a response object for you. If the return value is a string it's721converted into a response object with the string as response body, a722``200 OK`` status code and a :mimetype:`text/html` mimetype. If the723return value is a dict, :func:`jsonify` is called to produce a response.724The logic that Flask applies to converting return values into response725objects is as follows:7267271. If a response object of the correct type is returned it's directly728 returned from the view.7292. If it's a string, a response object is created with that data and730 the default parameters.7313. If it's a dict, a response object is created using ``jsonify``.7324. If a tuple is returned the items in the tuple can provide extra733 information. Such tuples have to be in the form734 ``(response, status)``, ``(response, headers)``, or735 ``(response, status, headers)``. The ``status`` value will override736 the status code and ``headers`` can be a list or dictionary of737 additional header values.7385. If none of that works, Flask will assume the return value is a739 valid WSGI application and convert that into a response object.740741If you want to get hold of the resulting response object inside the view742you can use the :func:`~flask.make_response` function.743744Imagine you have a view like this::745746 from flask import render_template747748 @app.errorhandler(404)749 def not_found(error):750 return render_template('error.html'), 404751752You just need to wrap the return expression with753:func:`~flask.make_response` and get the response object to modify it, then754return it::755756 from flask import make_response757758 @app.errorhandler(404)759 def not_found(error):760 resp = make_response(render_template('error.html'), 404)761 resp.headers['X-Something'] = 'A value'762 return resp763764765APIs with JSON766``````````````767768A common response format when writing an API is JSON. It's easy to get769started writing such an API with Flask. If you return a ``dict`` from a770view, it will be converted to a JSON response.771772.. code-block:: python773774 @app.route("/me")775 def me_api():776 user = get_current_user()777 return {778 "username": user.username,779 "theme": user.theme,780 "image": url_for("user_image", filename=user.image),781 }782783Depending on your API design, you may want to create JSON responses for784types other than ``dict``. In that case, use the785:func:`~flask.json.jsonify` function, which will serialize any supported786JSON data type. Or look into Flask community extensions that support787more complex applications.788789.. code-block:: python790791 from flask import jsonify792793 @app.route("/users")794 def users_api():795 users = get_all_users()796 return jsonify([user.to_json() for user in users])797798799.. _sessions:800801Sessions802--------803804In addition to the request object there is also a second object called805:class:`~flask.session` which allows you to store information specific to a806user from one request to the next. This is implemented on top of cookies807for you and signs the cookies cryptographically. What this means is that808the user could look at the contents of your cookie but not modify it,809unless they know the secret key used for signing.810811In order to use sessions you have to set a secret key. Here is how812sessions work::813814 from flask import session815816 # Set the secret key to some random bytes. Keep this really secret!817 app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'818819 @app.route('/')820 def index():821 if 'username' in session:822 return f'Logged in as {session["username"]}'823 return 'You are not logged in'824825 @app.route('/login', methods=['GET', 'POST'])826 def login():827 if request.method == 'POST':828 session['username'] = request.form['username']829 return redirect(url_for('index'))830 return '''831 <form method="post">832 <p><input type=text name=username>833 <p><input type=submit value=Login>834 </form>835 '''836837 @app.route('/logout')838 def logout():839 # remove the username from the session if it's there840 session.pop('username', None)841 return redirect(url_for('index'))842843.. admonition:: How to generate good secret keys844845 A secret key should be as random as possible. Your operating system has846 ways to generate pretty random data based on a cryptographic random847 generator. Use the following command to quickly generate a value for848 :attr:`Flask.secret_key` (or :data:`SECRET_KEY`)::849Merge branch '2.0.x'David Lordbefore adoption0ae0f59
lines 850–851why, one step back850 $ python -c 'import secrets; print(secrets.token_hex())'851 '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'add EditorConfigDavid Lordbefore adoption295e1e7
lines 852–913why, one step back852853A note on cookie-based sessions: Flask will take the values you put into the854session object and serialize them into a cookie. If you are finding some855values do not persist across requests, cookies are indeed enabled, and you are856not getting a clear error message, check the size of the cookie in your page857responses compared to the size supported by web browsers.858859Besides the default client-side based sessions, if you want to handle860sessions on the server-side instead, there are several861Flask extensions that support this.862863Message Flashing864----------------865866Good applications and user interfaces are all about feedback. If the user867does not get enough feedback they will probably end up hating the868application. Flask provides a really simple way to give feedback to a869user with the flashing system. The flashing system basically makes it870possible to record a message at the end of a request and access it on the next871(and only the next) request. This is usually combined with a layout872template to expose the message.873874To flash a message use the :func:`~flask.flash` method, to get hold of the875messages you can use :func:`~flask.get_flashed_messages` which is also876available in the templates. See :doc:`patterns/flashing` for a full877example.878879Logging880-------881882.. versionadded:: 0.3883884Sometimes you might be in a situation where you deal with data that885should be correct, but actually is not. For example you may have886some client-side code that sends an HTTP request to the server887but it's obviously malformed. This might be caused by a user tampering888with the data, or the client code failing. Most of the time it's okay889to reply with ``400 Bad Request`` in that situation, but sometimes890that won't do and the code has to continue working.891892You may still want to log that something fishy happened. This is where893loggers come in handy. As of Flask 0.3 a logger is preconfigured for you894to use.895896Here are some example log calls::897898 app.logger.debug('A value for debugging')899 app.logger.warning('A warning occurred (%d apples)', 42)900 app.logger.error('An error occurred')901902The attached :attr:`~flask.Flask.logger` is a standard logging903:class:`~logging.Logger`, so head over to the official :mod:`logging`904docs for more information.905906See :doc:`errorhandling`.907908909Hooking in WSGI Middleware910--------------------------911912To add WSGI middleware to your Flask application, wrap the application's913``wsgi_app`` attribute. For example, to apply Werkzeug'sMerge pull request #3965 from pallets/release-2.0.0rc1David Lordbefore adoption34eb0da
line 914why, one step back914:class:`~werkzeug.middleware.proxy_fix.ProxyFix` middleware for runningadd EditorConfigDavid Lordbefore adoption295e1e7
lines 915–938why, one step back915behind Nginx:916917.. code-block:: python918919 from werkzeug.middleware.proxy_fix import ProxyFix920 app.wsgi_app = ProxyFix(app.wsgi_app)921922Wrapping ``app.wsgi_app`` instead of ``app`` means that ``app`` still923points at your Flask application, not at the middleware, so you can924continue to use and configure ``app`` directly.925926Using Flask Extensions927----------------------928929Extensions are packages that help you accomplish common tasks. For930example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple931and easy to use with Flask.932933For more on Flask extensions, see :doc:`extensions`.934935Deploying to a Web Server936-------------------------937938Ready to deploy your new Flask app? See :doc:`deploying/index`.