Skip to content
Myr

quickstart.rst

This file

Path

docs/quickstart.rst

943 lines · 32.1 KiB

Last changed by

Merge branch '2.0.x'David Lordbefore adoptionedac7e3

History of this file

Take it

1Quickstart2==========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:4647.. tabs::4849   .. group-tab:: Bash5051      .. code-block:: text5253         $ export FLASK_APP=hello54         $ flask run55          * Running on http://127.0.0.1:5000/5657   .. group-tab:: CMD5859      .. code-block:: text6061         > set FLASK_APP=hello62         > flask run63          * Running on http://127.0.0.1:5000/6465   .. group-tab:: Powershell6667      .. code-block:: text6869         > $env:FLASK_APP = "hello"70         > flask run71          * Running on http://127.0.0.1:5000/7273.. 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.7879This 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.8586If another program is already using port 5000, you'll see87``OSError: [Errno 98]`` or ``OSError: [WinError 10013]`` when the88server tries to start. See :ref:`address-already-in-use` for how to89handle that.9091.. _public-server:9293.. admonition:: Externally Visible Server9495   If you run the server you will notice that the server is only accessible96   from your own computer, not from any other in the network.  This is the97   default because in debugging mode a user of the application can execute98   arbitrary Python code on your computer.99100   If you have the debugger disabled or trust the users on your network,101   you can make the server publicly available simply by adding102   ``--host=0.0.0.0`` to the command line::103104       $ flask run --host=0.0.0.0105106   This tells your operating system to listen on all public IPs.107108109What to do if the Server does not Start110---------------------------------------111112In case the :command:`python -m flask` fails or :command:`flask`113does not exist, there are multiple reasons this might be the case.114First of all you need to look at the error message.115116Old Version of Flask117````````````````````118119Versions of Flask older than 0.11 used to have different ways to start the120application.  In short, the :command:`flask` command did not exist, and121neither did :command:`python -m flask`.  In that case you have two options:122either upgrade to newer Flask versions or have a look at :doc:`/server`123to see the alternative method for running a server.124125Invalid Import Name126```````````````````127128The ``FLASK_APP`` environment variable is the name of the module to import at129:command:`flask run`. In case that module is incorrectly named you will get an130import error upon start (or if debug is enabled when you navigate to the131application). It will tell you what it tried to import and why it failed.132133The most common reason is a typo or because you did not actually create an134``app`` object.135136137Debug Mode138----------139140The ``flask run`` command can do more than just start the development141server. By enabling debug mode, the server will automatically reload if142code changes, and will show an interactive debugger in the browser if an143error occurs during a request.144145.. image:: _static/debugger.png146    :align: center147    :class: screenshot148    :alt: The interactive debugger in action.149150.. warning::151152    The debugger allows executing arbitrary Python code from the153    browser. It is protected by a pin, but still represents a major154    security risk. Do not run the development server or debugger in a155    production environment.156157To enable all development features, set the ``FLASK_ENV`` environment158variable to ``development`` before calling ``flask run``.159160.. tabs::161162   .. group-tab:: Bash163164      .. code-block:: text165166         $ export FLASK_ENV=development167         $ flask run168169   .. group-tab:: CMD170171      .. code-block:: text172173         > set FLASK_ENV=development174         > flask run175176   .. group-tab:: Powershell177178      .. code-block:: text179180         > $env:FLASK_ENV = "development"181         > flask run182183See also:184185-   :doc:`/server` and :doc:`/cli` for information about running in186    development mode.187-   :doc:`/debugging` for information about using the built-in debugger188    and other debuggers.189-   :doc:`/logging` and :doc:`/errorhandling` to log errors and display190    nice error pages.191192193HTML Escaping194-------------195196When returning HTML (the default response type in Flask), any197user-provided values rendered in the output must be escaped to protect198from injection attacks. HTML templates rendered with Jinja, introduced199later, will do this automatically.200201:func:`~markupsafe.escape`, shown here, can be used manually. It is202omitted in most examples for brevity, but you should always be aware of203how you're using untrusted data.204205.. code-block:: python206207    from markupsafe import escape208209    @app.route("/<name>")210    def hello(name):211        return f"Hello, {escape(name)}!"212213If a user managed to submit the name ``<script>alert("bad")</script>``,214escaping causes it to be rendered as text, rather than running the215script in the user's browser.216217``<name>`` in the route captures a value from the URL and passes it to218the view function. These variable rules are explained below.219220221Routing222-------223224Modern web applications use meaningful URLs to help users. Users are more225likely to like a page and come back if the page uses a meaningful URL they can226remember and use to directly visit a page.227228Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. ::229230    @app.route('/')231    def index():232        return 'Index Page'233234    @app.route('/hello')235    def hello():236        return 'Hello, World'237238You can do more! You can make parts of the URL dynamic and attach multiple239rules to a function.240241Variable Rules242``````````````243244You can add variable sections to a URL by marking sections with245``<variable_name>``. Your function then receives the ``<variable_name>``246as a keyword argument. Optionally, you can use a converter to specify the type247of the argument like ``<converter:variable_name>``. ::248249    from markupsafe import escape250251    @app.route('/user/<username>')252    def show_user_profile(username):253        # show the user profile for that user254        return f'User {escape(username)}'255256    @app.route('/post/<int:post_id>')257    def show_post(post_id):258        # show the post with the given id, the id is an integer259        return f'Post {post_id}'260261    @app.route('/path/<path:subpath>')262    def show_subpath(subpath):263        # show the subpath after /path/264        return f'Subpath {escape(subpath)}'265266Converter types:267268========== ==========================================269``string`` (default) accepts any text without a slash270``int``    accepts positive integers271``float``  accepts positive floating point values272``path``   like ``string`` but also accepts slashes273``uuid``   accepts UUID strings274========== ==========================================275276277Unique URLs / Redirection Behavior278``````````````````````````````````279280The following two rules differ in their use of a trailing slash. ::281282    @app.route('/projects/')283    def projects():284        return 'The project page'285286    @app.route('/about')287    def about():288        return 'The about page'289290The canonical URL for the ``projects`` endpoint has a trailing slash.291It's similar to a folder in a file system. If you access the URL without292a trailing slash (``/projects``), Flask redirects you to the canonical URL293with the trailing slash (``/projects/``).294295The canonical URL for the ``about`` endpoint does not have a trailing296slash. It's similar to the pathname of a file. Accessing the URL with a297trailing slash (``/about/``) produces a 404 "Not Found" error. This helps298keep URLs unique for these resources, which helps search engines avoid299indexing the same page twice.300301302.. _url-building:303304URL Building305````````````306307To build a URL to a specific function, use the :func:`~flask.url_for` function.308It accepts the name of the function as its first argument and any number of309keyword arguments, each corresponding to a variable part of the URL rule.310Unknown variable parts are appended to the URL as query parameters.311312Why would you want to build URLs using the URL reversing function313:func:`~flask.url_for` instead of hard-coding them into your templates?3143151. Reversing is often more descriptive than hard-coding the URLs.3162. You can change your URLs in one go instead of needing to remember to317   manually change hard-coded URLs.3183. URL building handles escaping of special characters transparently.3194. The generated paths are always absolute, avoiding unexpected behavior320   of relative paths in browsers.3215. If your application is placed outside the URL root, for example, in322   ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly323   handles that for you.324325For example, here we use the :meth:`~flask.Flask.test_request_context` method326to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context`327tells Flask to behave as though it's handling a request even while we use a328Python shell. See :ref:`context-locals`.329330.. code-block:: python331332    from flask import url_for333334    @app.route('/')335    def index():336        return 'index'337338    @app.route('/login')339    def login():340        return 'login'341342    @app.route('/user/<username>')343    def profile(username):344        return f'{username}\'s profile'345346    with app.test_request_context():347        print(url_for('index'))348        print(url_for('login'))349        print(url_for('login', next='/'))350        print(url_for('profile', username='John Doe'))351352.. code-block:: text353354    /355    /login356    /login?next=/357    /user/John%20Doe358359360HTTP Methods361````````````362363Web applications use different HTTP methods when accessing URLs. You should364familiarize yourself with the HTTP methods as you work with Flask. By default,365a route only answers to ``GET`` requests. You can use the ``methods`` argument366of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods.367::368369    from flask import request370371    @app.route('/login', methods=['GET', 'POST'])372    def login():373        if request.method == 'POST':374            return do_the_login()375        else:376            return show_the_login_form()377378If ``GET`` is present, Flask automatically adds support for the ``HEAD`` method379and handles ``HEAD`` requests according to the `HTTP RFC`_. Likewise,380``OPTIONS`` is automatically implemented for you.381382.. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt383384Static Files385------------386387Dynamic web applications also need static files.  That's usually where388the CSS and JavaScript files are coming from.  Ideally your web server is389configured to serve them for you, but during development Flask can do that390as well.  Just create a folder called :file:`static` in your package or next to391your module and it will be available at ``/static`` on the application.392393To generate URLs for static files, use the special ``'static'`` endpoint name::394395    url_for('static', filename='style.css')396397The file has to be stored on the filesystem as :file:`static/style.css`.398399Rendering Templates400-------------------401402Generating HTML from within Python is not fun, and actually pretty403cumbersome because you have to do the HTML escaping on your own to keep404the application secure.  Because of that Flask configures the `Jinja2405<https://palletsprojects.com/p/jinja/>`_ template engine for you automatically.406407To render a template you can use the :func:`~flask.render_template`408method.  All you have to do is provide the name of the template and the409variables you want to pass to the template engine as keyword arguments.410Here's a simple example of how to render a template::411412    from flask import render_template413414    @app.route('/hello/')415    @app.route('/hello/<name>')416    def hello(name=None):417        return render_template('hello.html', name=name)418419Flask will look for templates in the :file:`templates` folder.  So if your420application is a module, this folder is next to that module, if it's a421package it's actually inside your package:422423**Case 1**: a module::424425    /application.py426    /templates427        /hello.html428429**Case 2**: a package::430431    /application432        /__init__.py433        /templates434            /hello.html435436For templates you can use the full power of Jinja2 templates.  Head over437to the official `Jinja2 Template Documentation438<https://jinja.palletsprojects.com/templates/>`_ for more information.439440Here is an example template:441442.. sourcecode:: html+jinja443444    <!doctype html>445    <title>Hello from Flask</title>446    {% if name %}447      <h1>Hello {{ name }}!</h1>448    {% else %}449      <h1>Hello, World!</h1>450    {% endif %}451452Inside templates you also have access to the :data:`~flask.Flask.config`,453:class:`~flask.request`, :class:`~flask.session` and :class:`~flask.g` [#]_ objects454as well as the :func:`~flask.url_for` and :func:`~flask.get_flashed_messages` functions.455456Templates are especially useful if inheritance is used.  If you want to457know how that works, see :doc:`patterns/templateinheritance`. Basically458template inheritance makes it possible to keep certain elements on each459page (like header, navigation and footer).460461Automatic escaping is enabled, so if ``name`` contains HTML it will be escaped462automatically.  If you can trust a variable and you know that it will be463safe HTML (for example because it came from a module that converts wiki464markup to HTML) you can mark it as safe by using the465:class:`~markupsafe.Markup` class or by using the ``|safe`` filter in the466template.  Head over to the Jinja 2 documentation for more examples.467468Here is a basic introduction to how the :class:`~markupsafe.Markup` class works::469470    >>> from markupsafe import Markup471    >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'472    Markup('<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')473    >>> Markup.escape('<blink>hacker</blink>')474    Markup('&lt;blink&gt;hacker&lt;/blink&gt;')475    >>> Markup('<em>Marked up</em> &raquo; HTML').striptags()476    'Marked up » HTML'477478.. versionchanged:: 0.5479480   Autoescaping is no longer enabled for all templates.  The following481   extensions for templates trigger autoescaping: ``.html``, ``.htm``,482   ``.xml``, ``.xhtml``.  Templates loaded from a string will have483   autoescaping disabled.484485.. [#] Unsure what that :class:`~flask.g` object is? It's something in which486   you can store information for your own needs. See the documentation487   for :class:`flask.g` and :doc:`patterns/sqlite3`.488489490Accessing Request Data491----------------------492493For web applications it's crucial to react to the data a client sends to494the server.  In Flask this information is provided by the global495:class:`~flask.request` object.  If you have some experience with Python496you might be wondering how that object can be global and how Flask497manages to still be threadsafe.  The answer is context locals:498499500.. _context-locals:501502Context Locals503``````````````504505.. admonition:: Insider Information506507   If you want to understand how that works and how you can implement508   tests with context locals, read this section, otherwise just skip it.509510Certain objects in Flask are global objects, but not of the usual kind.511These objects are actually proxies to objects that are local to a specific512context.  What a mouthful.  But that is actually quite easy to understand.513514Imagine the context being the handling thread.  A request comes in and the515web server decides to spawn a new thread (or something else, the516underlying object is capable of dealing with concurrency systems other517than threads).  When Flask starts its internal request handling it518figures out that the current thread is the active context and binds the519current application and the WSGI environments to that context (thread).520It does that in an intelligent way so that one application can invoke another521application without breaking.522523So what does this mean to you?  Basically you can completely ignore that524this is the case unless you are doing something like unit testing.  You525will notice that code which depends on a request object will suddenly break526because there is no request object.  The solution is creating a request527object yourself and binding it to the context.  The easiest solution for528unit testing is to use the :meth:`~flask.Flask.test_request_context`529context manager.  In combination with the ``with`` statement it will bind a530test request so that you can interact with it.  Here is an example::531532    from flask import request533534    with app.test_request_context('/hello', method='POST'):535        # now you can do something with the request until the536        # end of the with block, such as basic assertions:537        assert request.path == '/hello'538        assert request.method == 'POST'539540The other possibility is passing a whole WSGI environment to the541:meth:`~flask.Flask.request_context` method::542543    with app.request_context(environ):544        assert request.method == 'POST'545546The Request Object547``````````````````548549The request object is documented in the API section and we will not cover550it here in detail (see :class:`~flask.Request`). Here is a broad overview of551some of the most common operations.  First of all you have to import it from552the ``flask`` module::553554    from flask import request555556The current request method is available by using the557:attr:`~flask.Request.method` attribute.  To access form data (data558transmitted in a ``POST`` or ``PUT`` request) you can use the559:attr:`~flask.Request.form` attribute.  Here is a full example of the two560attributes mentioned above::561562    @app.route('/login', methods=['POST', 'GET'])563    def login():564        error = None565        if request.method == 'POST':566            if valid_login(request.form['username'],567                           request.form['password']):568                return log_the_user_in(request.form['username'])569            else:570                error = 'Invalid username/password'571        # the code below is executed if the request method572        # was GET or the credentials were invalid573        return render_template('login.html', error=error)574575What happens if the key does not exist in the ``form`` attribute?  In that576case a special :exc:`KeyError` is raised.  You can catch it like a577standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request578error page is shown instead.  So for many situations you don't have to579deal with that problem.580581To access parameters submitted in the URL (``?key=value``) you can use the582:attr:`~flask.Request.args` attribute::583584    searchword = request.args.get('key', '')585586We recommend accessing URL parameters with `get` or by catching the587:exc:`KeyError` because users might change the URL and presenting them a 400588bad request page in that case is not user friendly.589590For a full list of methods and attributes of the request object, head over591to the :class:`~flask.Request` documentation.592593594File Uploads595````````````596597You can handle uploaded files with Flask easily.  Just make sure not to598forget to set the ``enctype="multipart/form-data"`` attribute on your HTML599form, otherwise the browser will not transmit your files at all.600601Uploaded files are stored in memory or at a temporary location on the602filesystem.  You can access those files by looking at the603:attr:`~flask.request.files` attribute on the request object.  Each604uploaded file is stored in that dictionary.  It behaves just like a605standard Python :class:`file` object, but it also has a606:meth:`~werkzeug.datastructures.FileStorage.save` method that607allows you to store that file on the filesystem of the server.608Here is a simple example showing how that works::609610    from flask import request611612    @app.route('/upload', methods=['GET', 'POST'])613    def upload_file():614        if request.method == 'POST':615            f = request.files['the_file']616            f.save('/var/www/uploads/uploaded_file.txt')617        ...618619If you want to know how the file was named on the client before it was620uploaded to your application, you can access the621:attr:`~werkzeug.datastructures.FileStorage.filename` attribute.622However please keep in mind that this value can be forged623so never ever trust that value.  If you want to use the filename624of the client to store the file on the server, pass it through the625:func:`~werkzeug.utils.secure_filename` function that626Werkzeug provides for you::627628    from werkzeug.utils import secure_filename629630    @app.route('/upload', methods=['GET', 'POST'])631    def upload_file():632        if request.method == 'POST':633            file = request.files['the_file']634            file.save(f"/var/www/uploads/{secure_filename(file.filename)}")635        ...636637For some better examples, see :doc:`patterns/fileuploads`.638639Cookies640```````641642To access cookies you can use the :attr:`~flask.Request.cookies`643attribute.  To set cookies you can use the644:attr:`~flask.Response.set_cookie` method of response objects.  The645:attr:`~flask.Request.cookies` attribute of request objects is a646dictionary with all the cookies the client transmits.  If you want to use647sessions, do not use the cookies directly but instead use the648:ref:`sessions` in Flask that add some security on top of cookies for you.649650Reading cookies::651652    from flask import request653654    @app.route('/')655    def index():656        username = request.cookies.get('username')657        # use cookies.get(key) instead of cookies[key] to not get a658        # KeyError if the cookie is missing.659660Storing cookies::661662    from flask import make_response663664    @app.route('/')665    def index():666        resp = make_response(render_template(...))667        resp.set_cookie('username', 'the username')668        return resp669670Note that cookies are set on response objects.  Since you normally671just return strings from the view functions Flask will convert them into672response objects for you.  If you explicitly want to do that you can use673the :meth:`~flask.make_response` function and then modify it.674675Sometimes you might want to set a cookie at a point where the response676object does not exist yet.  This is possible by utilizing the677:doc:`patterns/deferredcallbacks` pattern.678679For this also see :ref:`about-responses`.680681Redirects and Errors682--------------------683684To redirect a user to another endpoint, use the :func:`~flask.redirect`685function; to abort a request early with an error code, use the686:func:`~flask.abort` function::687688    from flask import abort, redirect, url_for689690    @app.route('/')691    def index():692        return redirect(url_for('login'))693694    @app.route('/login')695    def login():696        abort(401)697        this_is_never_executed()698699This is a rather pointless example because a user will be redirected from700the index to a page they cannot access (401 means access denied) but it701shows how that works.702703By default a black and white error page is shown for each error code.  If704you want to customize the error page, you can use the705:meth:`~flask.Flask.errorhandler` decorator::706707    from flask import render_template708709    @app.errorhandler(404)710    def page_not_found(error):711        return render_template('page_not_found.html'), 404712713Note the ``404`` after the :func:`~flask.render_template` call.  This714tells Flask that the status code of that page should be 404 which means715not found.  By default 200 is assumed which translates to: all went well.716717See :doc:`errorhandling` for more details.718719.. _about-responses:720721About Responses722---------------723724The return value from a view function is automatically converted into725a response object for you. If the return value is a string it's726converted into a response object with the string as response body, a727``200 OK`` status code and a :mimetype:`text/html` mimetype. If the728return value is a dict, :func:`jsonify` is called to produce a response.729The logic that Flask applies to converting return values into response730objects is as follows:7317321.  If a response object of the correct type is returned it's directly733    returned from the view.7342.  If it's a string, a response object is created with that data and735    the default parameters.7363.  If it's a dict, a response object is created using ``jsonify``.7374.  If a tuple is returned the items in the tuple can provide extra738    information. Such tuples have to be in the form739    ``(response, status)``, ``(response, headers)``, or740    ``(response, status, headers)``. The ``status`` value will override741    the status code and ``headers`` can be a list or dictionary of742    additional header values.7435.  If none of that works, Flask will assume the return value is a744    valid WSGI application and convert that into a response object.745746If you want to get hold of the resulting response object inside the view747you can use the :func:`~flask.make_response` function.748749Imagine you have a view like this::750751    from flask import render_template752753    @app.errorhandler(404)754    def not_found(error):755        return render_template('error.html'), 404756757You just need to wrap the return expression with758:func:`~flask.make_response` and get the response object to modify it, then759return it::760761    from flask import make_response762763    @app.errorhandler(404)764    def not_found(error):765        resp = make_response(render_template('error.html'), 404)766        resp.headers['X-Something'] = 'A value'767        return resp768769770APIs with JSON771``````````````772773A common response format when writing an API is JSON. It's easy to get774started writing such an API with Flask. If you return a ``dict`` from a775view, it will be converted to a JSON response.776777.. code-block:: python778779    @app.route("/me")780    def me_api():781        user = get_current_user()782        return {783            "username": user.username,784            "theme": user.theme,785            "image": url_for("user_image", filename=user.image),786        }787788Depending on your API design, you may want to create JSON responses for789types other than ``dict``. In that case, use the790:func:`~flask.json.jsonify` function, which will serialize any supported791JSON data type. Or look into Flask community extensions that support792more complex applications.793794.. code-block:: python795796    from flask import jsonify797798    @app.route("/users")799    def users_api():800        users = get_all_users()801        return jsonify([user.to_json() for user in users])802803804.. _sessions:805806Sessions807--------808809In addition to the request object there is also a second object called810:class:`~flask.session` which allows you to store information specific to a811user from one request to the next.  This is implemented on top of cookies812for you and signs the cookies cryptographically.  What this means is that813the user could look at the contents of your cookie but not modify it,814unless they know the secret key used for signing.815816In order to use sessions you have to set a secret key.  Here is how817sessions work::818819    from flask import session820821    # Set the secret key to some random bytes. Keep this really secret!822    app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'823824    @app.route('/')825    def index():826        if 'username' in session:827            return f'Logged in as {session["username"]}'828        return 'You are not logged in'829830    @app.route('/login', methods=['GET', 'POST'])831    def login():832        if request.method == 'POST':833            session['username'] = request.form['username']834            return redirect(url_for('index'))835        return '''836            <form method="post">837                <p><input type=text name=username>838                <p><input type=submit value=Login>839            </form>840        '''841842    @app.route('/logout')843    def logout():844        # remove the username from the session if it's there845        session.pop('username', None)846        return redirect(url_for('index'))847848.. admonition:: How to generate good secret keys849850    A secret key should be as random as possible. Your operating system has851    ways to generate pretty random data based on a cryptographic random852    generator. Use the following command to quickly generate a value for853    :attr:`Flask.secret_key` (or :data:`SECRET_KEY`)::854855        $ python -c 'import secrets; print(secrets.token_hex())'856        '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'857858A note on cookie-based sessions: Flask will take the values you put into the859session object and serialize them into a cookie.  If you are finding some860values do not persist across requests, cookies are indeed enabled, and you are861not getting a clear error message, check the size of the cookie in your page862responses compared to the size supported by web browsers.863864Besides the default client-side based sessions, if you want to handle865sessions on the server-side instead, there are several866Flask extensions that support this.867868Message Flashing869----------------870871Good applications and user interfaces are all about feedback.  If the user872does not get enough feedback they will probably end up hating the873application.  Flask provides a really simple way to give feedback to a874user with the flashing system.  The flashing system basically makes it875possible to record a message at the end of a request and access it on the next876(and only the next) request.  This is usually combined with a layout877template to expose the message.878879To flash a message use the :func:`~flask.flash` method, to get hold of the880messages you can use :func:`~flask.get_flashed_messages` which is also881available in the templates. See :doc:`patterns/flashing` for a full882example.883884Logging885-------886887.. versionadded:: 0.3888889Sometimes you might be in a situation where you deal with data that890should be correct, but actually is not.  For example you may have891some client-side code that sends an HTTP request to the server892but it's obviously malformed.  This might be caused by a user tampering893with the data, or the client code failing.  Most of the time it's okay894to reply with ``400 Bad Request`` in that situation, but sometimes895that won't do and the code has to continue working.896897You may still want to log that something fishy happened.  This is where898loggers come in handy.  As of Flask 0.3 a logger is preconfigured for you899to use.900901Here are some example log calls::902903    app.logger.debug('A value for debugging')904    app.logger.warning('A warning occurred (%d apples)', 42)905    app.logger.error('An error occurred')906907The attached :attr:`~flask.Flask.logger` is a standard logging908:class:`~logging.Logger`, so head over to the official :mod:`logging`909docs for more information.910911See :doc:`errorhandling`.912913914Hooking in WSGI Middleware915--------------------------916917To add WSGI middleware to your Flask application, wrap the application's918``wsgi_app`` attribute. For example, to apply Werkzeug's919:class:`~werkzeug.middleware.proxy_fix.ProxyFix` middleware for running920behind Nginx:921922.. code-block:: python923924    from werkzeug.middleware.proxy_fix import ProxyFix925    app.wsgi_app = ProxyFix(app.wsgi_app)926927Wrapping ``app.wsgi_app`` instead of ``app`` means that ``app`` still928points at your Flask application, not at the middleware, so you can929continue to use and configure ``app`` directly.930931Using Flask Extensions932----------------------933934Extensions are packages that help you accomplish common tasks. For935example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple936and easy to use with Flask.937938For more on Flask extensions, see :doc:`extensions`.939940Deploying to a Web Server941-------------------------942943Ready to deploy your new Flask app? See :doc:`deploying/index`.