Skip to content
Myr

quickstart.rst

This file

Path

docs/quickstart.rst

932 lines · 31.5 KiB

Last changed by

Merge remote-tracking branch 'origin/1.1.x' into release-2.0.0rc1David Lordbefore adoption6f09b4b

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=hello.py54         $ flask run55          * Running on http://127.0.0.1:5000/5657   .. group-tab:: CMD5859      .. code-block:: text6061         > set FLASK_APP=hello.py62         > flask run63          * Running on http://127.0.0.1:5000/6465   .. group-tab:: Powershell6667      .. code-block:: text6869         > $env:FLASK_APP = "hello.py"70         > flask run71          * Running on http://127.0.0.1:5000/7273This launches a very simple builtin server, which is good enough for74testing but probably not what you want to use in production. For75deployment options see :doc:`deploying/index`.7677Now head over to http://127.0.0.1:5000/, and you should see your hello78world greeting.7980.. _public-server:8182.. admonition:: Externally Visible Server8384   If you run the server you will notice that the server is only accessible85   from your own computer, not from any other in the network.  This is the86   default because in debugging mode a user of the application can execute87   arbitrary Python code on your computer.8889   If you have the debugger disabled or trust the users on your network,90   you can make the server publicly available simply by adding91   ``--host=0.0.0.0`` to the command line::9293       $ flask run --host=0.0.0.09495   This tells your operating system to listen on all public IPs.969798What to do if the Server does not Start99---------------------------------------100101In case the :command:`python -m flask` fails or :command:`flask`102does not exist, there are multiple reasons this might be the case.103First of all you need to look at the error message.104105Old Version of Flask106````````````````````107108Versions of Flask older than 0.11 used to have different ways to start the109application.  In short, the :command:`flask` command did not exist, and110neither did :command:`python -m flask`.  In that case you have two options:111either upgrade to newer Flask versions or have a look at :doc:`/server`112to see the alternative method for running a server.113114Invalid Import Name115```````````````````116117The ``FLASK_APP`` environment variable is the name of the module to import at118:command:`flask run`. In case that module is incorrectly named you will get an119import error upon start (or if debug is enabled when you navigate to the120application). It will tell you what it tried to import and why it failed.121122The most common reason is a typo or because you did not actually create an123``app`` object.124125126Debug Mode127----------128129The ``flask run`` command can do more than just start the development130server. By enabling debug mode, the server will automatically reload if131code changes, and will show an interactive debugger in the browser if an132error occurs during a request.133134.. image:: _static/debugger.png135    :align: center136    :class: screenshot137    :alt: The interactive debugger in action.138139.. warning::140141    The debugger allows executing arbitrary Python code from the142    browser. It is protected by a pin, but still represents a major143    security risk. Do not run the development server or debugger in a144    production environment.145146To enable all development features, set the ``FLASK_ENV`` environment147variable to ``development`` before calling ``flask run``.148149.. tabs::150151   .. group-tab:: Bash152153      .. code-block:: text154155         $ export FLASK_ENV=development156         $ flask run157158   .. group-tab:: CMD159160      .. code-block:: text161162         > set FLASK_ENV=development163         > flask run164165   .. group-tab:: Powershell166167      .. code-block:: text168169         > $env:FLASK_ENV = "development"170         > flask run171172See also:173174-   :doc:`/server` and :doc:`/cli` for information about running in175    development mode.176-   :doc:`/debugging` for information about using the built-in debugger177    and other debuggers.178-   :doc:`/logging` and :doc:`/errorhandling` to log errors and display179    nice error pages.180181182HTML Escaping183-------------184185When returning HTML (the default response type in Flask), any186user-provided values rendered in the output must be escaped to protect187from injection attacks. HTML templates rendered with Jinja, introduced188later, will do this automatically.189190:func:`~markupsafe.escape`, shown here, can be used manually. It is191omitted in most examples for brevity, but you should always be aware of192how you're using untrusted data.193194.. code-block:: python195196    from markupsafe import escape197198    @app.route("/<name>")199    def hello(name):200        return f"Hello, {escape(name)}!"201202If a user managed to submit the name ``<script>alert("bad")</script>``,203escaping causes it to be rendered as text, rather than running the204script in the user's browser.205206``<name>`` in the route captures a value from the URL and passes it to207the view function. These variable rules are explained below.208209210Routing211-------212213Modern web applications use meaningful URLs to help users. Users are more214likely to like a page and come back if the page uses a meaningful URL they can215remember and use to directly visit a page.216217Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. ::218219    @app.route('/')220    def index():221        return 'Index Page'222223    @app.route('/hello')224    def hello():225        return 'Hello, World'226227You can do more! You can make parts of the URL dynamic and attach multiple228rules to a function.229230Variable Rules231``````````````232233You can add variable sections to a URL by marking sections with234``<variable_name>``. Your function then receives the ``<variable_name>``235as a keyword argument. Optionally, you can use a converter to specify the type236of the argument like ``<converter:variable_name>``. ::237238    from markupsafe import escape239240    @app.route('/user/<username>')241    def show_user_profile(username):242        # show the user profile for that user243        return f'User {username}'244245    @app.route('/post/<int:post_id>')246    def show_post(post_id):247        # show the post with the given id, the id is an integer248        return f'Post {post_id}'249250    @app.route('/path/<path:subpath>')251    def show_subpath(subpath):252        # show the subpath after /path/253        return f'Subpath {subpath}'254255Converter types:256257========== ==========================================258``string`` (default) accepts any text without a slash259``int``    accepts positive integers260``float``  accepts positive floating point values261``path``   like ``string`` but also accepts slashes262``uuid``   accepts UUID strings263========== ==========================================264265266Unique URLs / Redirection Behavior267``````````````````````````````````268269The following two rules differ in their use of a trailing slash. ::270271    @app.route('/projects/')272    def projects():273        return 'The project page'274275    @app.route('/about')276    def about():277        return 'The about page'278279The canonical URL for the ``projects`` endpoint has a trailing slash.280It's similar to a folder in a file system. If you access the URL without281a trailing slash (``/projects``), Flask redirects you to the canonical URL282with the trailing slash (``/projects/``).283284The canonical URL for the ``about`` endpoint does not have a trailing285slash. It's similar to the pathname of a file. Accessing the URL with a286trailing slash (``/about/``) produces a 404 "Not Found" error. This helps287keep URLs unique for these resources, which helps search engines avoid288indexing the same page twice.289290291.. _url-building:292293URL Building294````````````295296To build a URL to a specific function, use the :func:`~flask.url_for` function.297It accepts the name of the function as its first argument and any number of298keyword arguments, each corresponding to a variable part of the URL rule.299Unknown variable parts are appended to the URL as query parameters.300301Why would you want to build URLs using the URL reversing function302:func:`~flask.url_for` instead of hard-coding them into your templates?3033041. Reversing is often more descriptive than hard-coding the URLs.3052. You can change your URLs in one go instead of needing to remember to306   manually change hard-coded URLs.3073. URL building handles escaping of special characters transparently.3084. The generated paths are always absolute, avoiding unexpected behavior309   of relative paths in browsers.3105. If your application is placed outside the URL root, for example, in311   ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly312   handles that for you.313314For example, here we use the :meth:`~flask.Flask.test_request_context` method315to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context`316tells Flask to behave as though it's handling a request even while we use a317Python shell. See :ref:`context-locals`.318319.. code-block:: python320321    from flask import url_for322323    @app.route('/')324    def index():325        return 'index'326327    @app.route('/login')328    def login():329        return 'login'330331    @app.route('/user/<username>')332    def profile(username):333        return f'{username}\'s profile'334335    with app.test_request_context():336        print(url_for('index'))337        print(url_for('login'))338        print(url_for('login', next='/'))339        print(url_for('profile', username='John Doe'))340341.. code-block:: text342343    /344    /login345    /login?next=/346    /user/John%20Doe347348349HTTP Methods350````````````351352Web applications use different HTTP methods when accessing URLs. You should353familiarize yourself with the HTTP methods as you work with Flask. By default,354a route only answers to ``GET`` requests. You can use the ``methods`` argument355of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods.356::357358    from flask import request359360    @app.route('/login', methods=['GET', 'POST'])361    def login():362        if request.method == 'POST':363            return do_the_login()364        else:365            return show_the_login_form()366367If ``GET`` is present, Flask automatically adds support for the ``HEAD`` method368and handles ``HEAD`` requests according to the `HTTP RFC`_. Likewise,369``OPTIONS`` is automatically implemented for you.370371.. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt372373Static Files374------------375376Dynamic web applications also need static files.  That's usually where377the CSS and JavaScript files are coming from.  Ideally your web server is378configured to serve them for you, but during development Flask can do that379as well.  Just create a folder called :file:`static` in your package or next to380your module and it will be available at ``/static`` on the application.381382To generate URLs for static files, use the special ``'static'`` endpoint name::383384    url_for('static', filename='style.css')385386The file has to be stored on the filesystem as :file:`static/style.css`.387388Rendering Templates389-------------------390391Generating HTML from within Python is not fun, and actually pretty392cumbersome because you have to do the HTML escaping on your own to keep393the application secure.  Because of that Flask configures the `Jinja2394<https://palletsprojects.com/p/jinja/>`_ template engine for you automatically.395396To render a template you can use the :func:`~flask.render_template`397method.  All you have to do is provide the name of the template and the398variables you want to pass to the template engine as keyword arguments.399Here's a simple example of how to render a template::400401    from flask import render_template402403    @app.route('/hello/')404    @app.route('/hello/<name>')405    def hello(name=None):406        return render_template('hello.html', name=name)407408Flask will look for templates in the :file:`templates` folder.  So if your409application is a module, this folder is next to that module, if it's a410package it's actually inside your package:411412**Case 1**: a module::413414    /application.py415    /templates416        /hello.html417418**Case 2**: a package::419420    /application421        /__init__.py422        /templates423            /hello.html424425For templates you can use the full power of Jinja2 templates.  Head over426to the official `Jinja2 Template Documentation427<https://jinja.palletsprojects.com/templates/>`_ for more information.428429Here is an example template:430431.. sourcecode:: html+jinja432433    <!doctype html>434    <title>Hello from Flask</title>435    {% if name %}436      <h1>Hello {{ name }}!</h1>437    {% else %}438      <h1>Hello, World!</h1>439    {% endif %}440441Inside templates you also have access to the :class:`~flask.request`,442:class:`~flask.session` and :class:`~flask.g` [#]_ objects443as well as the :func:`~flask.get_flashed_messages` function.444445Templates are especially useful if inheritance is used.  If you want to446know how that works, see :doc:`patterns/templateinheritance`. Basically447template inheritance makes it possible to keep certain elements on each448page (like header, navigation and footer).449450Automatic escaping is enabled, so if ``name`` contains HTML it will be escaped451automatically.  If you can trust a variable and you know that it will be452safe HTML (for example because it came from a module that converts wiki453markup to HTML) you can mark it as safe by using the454:class:`~markupsafe.Markup` class or by using the ``|safe`` filter in the455template.  Head over to the Jinja 2 documentation for more examples.456457Here is a basic introduction to how the :class:`~markupsafe.Markup` class works::458459    >>> from markupsafe import Markup460    >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'461    Markup('<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')462    >>> Markup.escape('<blink>hacker</blink>')463    Markup('&lt;blink&gt;hacker&lt;/blink&gt;')464    >>> Markup('<em>Marked up</em> &raquo; HTML').striptags()465    'Marked up \xbb HTML'466467.. versionchanged:: 0.5468469   Autoescaping is no longer enabled for all templates.  The following470   extensions for templates trigger autoescaping: ``.html``, ``.htm``,471   ``.xml``, ``.xhtml``.  Templates loaded from a string will have472   autoescaping disabled.473474.. [#] Unsure what that :class:`~flask.g` object is? It's something in which475   you can store information for your own needs. See the documentation476   for :class:`flask.g` and :doc:`patterns/sqlite3`.477478479Accessing Request Data480----------------------481482For web applications it's crucial to react to the data a client sends to483the server.  In Flask this information is provided by the global484:class:`~flask.request` object.  If you have some experience with Python485you might be wondering how that object can be global and how Flask486manages to still be threadsafe.  The answer is context locals:487488489.. _context-locals:490491Context Locals492``````````````493494.. admonition:: Insider Information495496   If you want to understand how that works and how you can implement497   tests with context locals, read this section, otherwise just skip it.498499Certain objects in Flask are global objects, but not of the usual kind.500These objects are actually proxies to objects that are local to a specific501context.  What a mouthful.  But that is actually quite easy to understand.502503Imagine the context being the handling thread.  A request comes in and the504web server decides to spawn a new thread (or something else, the505underlying object is capable of dealing with concurrency systems other506than threads).  When Flask starts its internal request handling it507figures out that the current thread is the active context and binds the508current application and the WSGI environments to that context (thread).509It does that in an intelligent way so that one application can invoke another510application without breaking.511512So what does this mean to you?  Basically you can completely ignore that513this is the case unless you are doing something like unit testing.  You514will notice that code which depends on a request object will suddenly break515because there is no request object.  The solution is creating a request516object yourself and binding it to the context.  The easiest solution for517unit testing is to use the :meth:`~flask.Flask.test_request_context`518context manager.  In combination with the ``with`` statement it will bind a519test request so that you can interact with it.  Here is an example::520521    from flask import request522523    with app.test_request_context('/hello', method='POST'):524        # now you can do something with the request until the525        # end of the with block, such as basic assertions:526        assert request.path == '/hello'527        assert request.method == 'POST'528529The other possibility is passing a whole WSGI environment to the530:meth:`~flask.Flask.request_context` method::531532    with app.request_context(environ):533        assert request.method == 'POST'534535The Request Object536``````````````````537538The request object is documented in the API section and we will not cover539it here in detail (see :class:`~flask.Request`). Here is a broad overview of540some of the most common operations.  First of all you have to import it from541the ``flask`` module::542543    from flask import request544545The current request method is available by using the546:attr:`~flask.Request.method` attribute.  To access form data (data547transmitted in a ``POST`` or ``PUT`` request) you can use the548:attr:`~flask.Request.form` attribute.  Here is a full example of the two549attributes mentioned above::550551    @app.route('/login', methods=['POST', 'GET'])552    def login():553        error = None554        if request.method == 'POST':555            if valid_login(request.form['username'],556                           request.form['password']):557                return log_the_user_in(request.form['username'])558            else:559                error = 'Invalid username/password'560        # the code below is executed if the request method561        # was GET or the credentials were invalid562        return render_template('login.html', error=error)563564What happens if the key does not exist in the ``form`` attribute?  In that565case a special :exc:`KeyError` is raised.  You can catch it like a566standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request567error page is shown instead.  So for many situations you don't have to568deal with that problem.569570To access parameters submitted in the URL (``?key=value``) you can use the571:attr:`~flask.Request.args` attribute::572573    searchword = request.args.get('key', '')574575We recommend accessing URL parameters with `get` or by catching the576:exc:`KeyError` because users might change the URL and presenting them a 400577bad request page in that case is not user friendly.578579For a full list of methods and attributes of the request object, head over580to the :class:`~flask.Request` documentation.581582583File Uploads584````````````585586You can handle uploaded files with Flask easily.  Just make sure not to587forget to set the ``enctype="multipart/form-data"`` attribute on your HTML588form, otherwise the browser will not transmit your files at all.589590Uploaded files are stored in memory or at a temporary location on the591filesystem.  You can access those files by looking at the592:attr:`~flask.request.files` attribute on the request object.  Each593uploaded file is stored in that dictionary.  It behaves just like a594standard Python :class:`file` object, but it also has a595:meth:`~werkzeug.datastructures.FileStorage.save` method that596allows you to store that file on the filesystem of the server.597Here is a simple example showing how that works::598599    from flask import request600601    @app.route('/upload', methods=['GET', 'POST'])602    def upload_file():603        if request.method == 'POST':604            f = request.files['the_file']605            f.save('/var/www/uploads/uploaded_file.txt')606        ...607608If you want to know how the file was named on the client before it was609uploaded to your application, you can access the610:attr:`~werkzeug.datastructures.FileStorage.filename` attribute.611However please keep in mind that this value can be forged612so never ever trust that value.  If you want to use the filename613of the client to store the file on the server, pass it through the614:func:`~werkzeug.utils.secure_filename` function that615Werkzeug provides for you::616617    from werkzeug.utils import secure_filename618619    @app.route('/upload', methods=['GET', 'POST'])620    def upload_file():621        if request.method == 'POST':622            file = request.files['the_file']623            file.save(f"/var/www/uploads/{secure_filename(f.filename)}")624        ...625626For some better examples, see :doc:`patterns/fileuploads`.627628Cookies629```````630631To access cookies you can use the :attr:`~flask.Request.cookies`632attribute.  To set cookies you can use the633:attr:`~flask.Response.set_cookie` method of response objects.  The634:attr:`~flask.Request.cookies` attribute of request objects is a635dictionary with all the cookies the client transmits.  If you want to use636sessions, do not use the cookies directly but instead use the637:ref:`sessions` in Flask that add some security on top of cookies for you.638639Reading cookies::640641    from flask import request642643    @app.route('/')644    def index():645        username = request.cookies.get('username')646        # use cookies.get(key) instead of cookies[key] to not get a647        # KeyError if the cookie is missing.648649Storing cookies::650651    from flask import make_response652653    @app.route('/')654    def index():655        resp = make_response(render_template(...))656        resp.set_cookie('username', 'the username')657        return resp658659Note that cookies are set on response objects.  Since you normally660just return strings from the view functions Flask will convert them into661response objects for you.  If you explicitly want to do that you can use662the :meth:`~flask.make_response` function and then modify it.663664Sometimes you might want to set a cookie at a point where the response665object does not exist yet.  This is possible by utilizing the666:doc:`patterns/deferredcallbacks` pattern.667668For this also see :ref:`about-responses`.669670Redirects and Errors671--------------------672673To redirect a user to another endpoint, use the :func:`~flask.redirect`674function; to abort a request early with an error code, use the675:func:`~flask.abort` function::676677    from flask import abort, redirect, url_for678679    @app.route('/')680    def index():681        return redirect(url_for('login'))682683    @app.route('/login')684    def login():685        abort(401)686        this_is_never_executed()687688This is a rather pointless example because a user will be redirected from689the index to a page they cannot access (401 means access denied) but it690shows how that works.691692By default a black and white error page is shown for each error code.  If693you want to customize the error page, you can use the694:meth:`~flask.Flask.errorhandler` decorator::695696    from flask import render_template697698    @app.errorhandler(404)699    def page_not_found(error):700        return render_template('page_not_found.html'), 404701702Note the ``404`` after the :func:`~flask.render_template` call.  This703tells Flask that the status code of that page should be 404 which means704not found.  By default 200 is assumed which translates to: all went well.705706See :doc:`errorhandling` for more details.707708.. _about-responses:709710About Responses711---------------712713The return value from a view function is automatically converted into714a response object for you. If the return value is a string it's715converted into a response object with the string as response body, a716``200 OK`` status code and a :mimetype:`text/html` mimetype. If the717return value is a dict, :func:`jsonify` is called to produce a response.718The logic that Flask applies to converting return values into response719objects is as follows:7207211.  If a response object of the correct type is returned it's directly722    returned from the view.7232.  If it's a string, a response object is created with that data and724    the default parameters.7253.  If it's a dict, a response object is created using ``jsonify``.7264.  If a tuple is returned the items in the tuple can provide extra727    information. Such tuples have to be in the form728    ``(response, status)``, ``(response, headers)``, or729    ``(response, status, headers)``. The ``status`` value will override730    the status code and ``headers`` can be a list or dictionary of731    additional header values.7325.  If none of that works, Flask will assume the return value is a733    valid WSGI application and convert that into a response object.734735If you want to get hold of the resulting response object inside the view736you can use the :func:`~flask.make_response` function.737738Imagine you have a view like this::739740    from flask import render_template741742    @app.errorhandler(404)743    def not_found(error):744        return render_template('error.html'), 404745746You just need to wrap the return expression with747:func:`~flask.make_response` and get the response object to modify it, then748return it::749750    from flask import make_response751752    @app.errorhandler(404)753    def not_found(error):754        resp = make_response(render_template('error.html'), 404)755        resp.headers['X-Something'] = 'A value'756        return resp757758759APIs with JSON760``````````````761762A common response format when writing an API is JSON. It's easy to get763started writing such an API with Flask. If you return a ``dict`` from a764view, it will be converted to a JSON response.765766.. code-block:: python767768    @app.route("/me")769    def me_api():770        user = get_current_user()771        return {772            "username": user.username,773            "theme": user.theme,774            "image": url_for("user_image", filename=user.image),775        }776777Depending on your API design, you may want to create JSON responses for778types other than ``dict``. In that case, use the779:func:`~flask.json.jsonify` function, which will serialize any supported780JSON data type. Or look into Flask community extensions that support781more complex applications.782783.. code-block:: python784785    from flask import jsonify786787    @app.route("/users")788    def users_api():789        users = get_all_users()790        return jsonify([user.to_json() for user in users])791792793.. _sessions:794795Sessions796--------797798In addition to the request object there is also a second object called799:class:`~flask.session` which allows you to store information specific to a800user from one request to the next.  This is implemented on top of cookies801for you and signs the cookies cryptographically.  What this means is that802the user could look at the contents of your cookie but not modify it,803unless they know the secret key used for signing.804805In order to use sessions you have to set a secret key.  Here is how806sessions work::807808    from flask import session809810    # Set the secret key to some random bytes. Keep this really secret!811    app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'812813    @app.route('/')814    def index():815        if 'username' in session:816            return f'Logged in as {session["username"]}'817        return 'You are not logged in'818819    @app.route('/login', methods=['GET', 'POST'])820    def login():821        if request.method == 'POST':822            session['username'] = request.form['username']823            return redirect(url_for('index'))824        return '''825            <form method="post">826                <p><input type=text name=username>827                <p><input type=submit value=Login>828            </form>829        '''830831    @app.route('/logout')832    def logout():833        # remove the username from the session if it's there834        session.pop('username', None)835        return redirect(url_for('index'))836837.. admonition:: How to generate good secret keys838839    A secret key should be as random as possible. Your operating system has840    ways to generate pretty random data based on a cryptographic random841    generator. Use the following command to quickly generate a value for842    :attr:`Flask.secret_key` (or :data:`SECRET_KEY`)::843844        $ python -c 'import os; print(os.urandom(16))'845        b'_5#y2L"F4Q8z\n\xec]/'846847A note on cookie-based sessions: Flask will take the values you put into the848session object and serialize them into a cookie.  If you are finding some849values do not persist across requests, cookies are indeed enabled, and you are850not getting a clear error message, check the size of the cookie in your page851responses compared to the size supported by web browsers.852853Besides the default client-side based sessions, if you want to handle854sessions on the server-side instead, there are several855Flask extensions that support this.856857Message Flashing858----------------859860Good applications and user interfaces are all about feedback.  If the user861does not get enough feedback they will probably end up hating the862application.  Flask provides a really simple way to give feedback to a863user with the flashing system.  The flashing system basically makes it864possible to record a message at the end of a request and access it on the next865(and only the next) request.  This is usually combined with a layout866template to expose the message.867868To flash a message use the :func:`~flask.flash` method, to get hold of the869messages you can use :func:`~flask.get_flashed_messages` which is also870available in the templates. See :doc:`patterns/flashing` for a full871example.872873Logging874-------875876.. versionadded:: 0.3877878Sometimes you might be in a situation where you deal with data that879should be correct, but actually is not.  For example you may have880some client-side code that sends an HTTP request to the server881but it's obviously malformed.  This might be caused by a user tampering882with the data, or the client code failing.  Most of the time it's okay883to reply with ``400 Bad Request`` in that situation, but sometimes884that won't do and the code has to continue working.885886You may still want to log that something fishy happened.  This is where887loggers come in handy.  As of Flask 0.3 a logger is preconfigured for you888to use.889890Here are some example log calls::891892    app.logger.debug('A value for debugging')893    app.logger.warning('A warning occurred (%d apples)', 42)894    app.logger.error('An error occurred')895896The attached :attr:`~flask.Flask.logger` is a standard logging897:class:`~logging.Logger`, so head over to the official :mod:`logging`898docs for more information.899900See :doc:`errorhandling`.901902903Hooking in WSGI Middleware904--------------------------905906To add WSGI middleware to your Flask application, wrap the application's907``wsgi_app`` attribute. For example, to apply Werkzeug's908:class:`~werkzeug.middleware.proxy_fix.ProxyFix` middleware for running909behind Nginx:910911.. code-block:: python912913    from werkzeug.middleware.proxy_fix import ProxyFix914    app.wsgi_app = ProxyFix(app.wsgi_app)915916Wrapping ``app.wsgi_app`` instead of ``app`` means that ``app`` still917points at your Flask application, not at the middleware, so you can918continue to use and configure ``app`` directly.919920Using Flask Extensions921----------------------922923Extensions are packages that help you accomplish common tasks. For924example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple925and easy to use with Flask.926927For more on Flask extensions, see :doc:`extensions`.928929Deploying to a Web Server930-------------------------931932Ready to deploy your new Flask app? See :doc:`deploying/index`.