Skip to content
Myr

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 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.. code-block:: text4849    $ 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"6162This 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`.6566Now head over to http://127.0.0.1:5000/, and you should see your hello67world greeting.6869.. _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::8182       $ flask run --host=0.0.0.08384   This tells your operating system to listen on all public IPs.858687What to do if the Server does not Start88---------------------------------------8990In 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.9394Old 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:100either upgrade to newer Flask versions or have a look at :doc:`/server`101to see the alternative method for running a server.102103Invalid 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----------118119(Want to just log errors and stack traces? See :doc:`errorhandling`)120121The :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``.144145There are more parameters that are explained in :doc:`/server`.146147.. 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`_.163164.. _Werkzeug documentation: https://werkzeug.palletsprojects.com/debug/#using-the-debugger165166Have another debugger in mind? See :ref:`working-with-debuggers`.167168169HTML 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.195196197Routing198-------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>``. ::224225    from markupsafe import escape226227    @app.route('/user/<username>')228    def show_user_profile(username):229        # show the user profile for that user230        return f'User {username}'231232    @app.route('/post/<int:post_id>')233    def show_post(post_id):234        # show the post with the given id, the id is an integer235        return f'Post {post_id}'236237    @app.route('/path/<path:subpath>')238    def show_subpath(subpath):239        # show the subpath after /path/240        return f'Subpath {subpath}'241242Converter 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========== ==========================================251252253Unique 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 to293   manually change hard-coded URLs.2943. URL building handles escaping of special characters transparently.2954. 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, in298   ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly299   handles that for you.300301For 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 a304Python shell. See :ref:`context-locals`.305306.. code-block:: python307308    from flask import url_for309310    @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):320        return f'{username}\'s profile'321322    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'))327328.. code-block:: text329330    /331    /login332    /login?next=/333    /user/John%20Doe334335336HTTP 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::344345    from flask import request346347    @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`` method355and handles ``HEAD`` requests according to the `HTTP RFC`_. Likewise,356``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 `Jinja2381<https://palletsprojects.com/p/jinja/>`_ template engine for you automatically.382383To 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 Documentation414<https://jinja.palletsprojects.com/templates/>`_ for more information.415416Here 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 to433know how that works, see :doc:`patterns/templateinheritance`. Basically434template inheritance makes it possible to keep certain elements on each435page (like header, navigation and footer).436437Automatic 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 the441:class:`~markupsafe.Markup` class or by using the ``|safe`` filter in the442template.  Head over to the Jinja 2 documentation for more examples.443444Here is a basic introduction to how the :class:`~markupsafe.Markup` class works::445446    >>> from markupsafe import Markup447    >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'448    Markup('<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')449    >>> Markup.escape('<blink>hacker</blink>')450    Markup('&lt;blink&gt;hacker&lt;/blink&gt;')451    >>> Markup('<em>Marked up</em> &raquo; HTML').striptags()452    'Marked up \xbb HTML'453454.. 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 which462   you can store information for your own needs. See the documentation463   for :class:`flask.g` and :doc:`patterns/sqlite3`.464465466Accessing 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 a582: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::585586    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 the597: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 that602Werkzeug 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':609            file = request.files['the_file']610            file.save(f"/var/www/uploads/{secure_filename(f.filename)}")611        ...612613For some better examples, see :doc:`patterns/fileuploads`.614615Cookies616```````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 the653:doc:`patterns/deferredcallbacks` pattern.654655For 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.692693See :doc:`errorhandling` for more details.694695.. _about-responses:696697About Responses698---------------699700The 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:7077081.  If a response object of the correct type is returned it's directly709    returned from the view.7102.  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 a720    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::726727    from flask import render_template728729    @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::736737    from flask import make_response738739    @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 resp744745746APIs 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:: python771772    from flask import jsonify773774    @app.route("/users")775    def users_api():776        users = get_all_users()777        return jsonify([user.to_json() for user in users])778779780.. _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::794795    from flask import session796797    # 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:803            return f'Logged in as {session["username"]}'804        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 also857available in the templates. See :doc:`patterns/flashing` for a full858example.859860Logging861-------862863.. versionadded:: 0.3864865Sometimes you might be in a situation where you deal with data that866should 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.872873You 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 logging884:class:`~logging.Logger`, so head over to the official :mod:`logging`885docs for more information.886887See :doc:`errorhandling`.888889890Hooking in WSGI Middleware891--------------------------892893To 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:897898.. 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.906907Using 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.913914For more on Flask extensions, see :doc:`extensions`.915916Deploying to a Web Server917-------------------------918919Ready to deploy your new Flask app? See :doc:`deploying/index`.