Skip to content
Myr

quickstart.rst

This file

Path

docs/quickstart.rst

899 lines · 31.0 KiB

Last changed by

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

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 ``flask`` command or43``python -m flask``. You need to tell the Flask where your application44is with the ``-app`` option.4546.. code-block:: text4748    $ flask --app hello run49     * Serving Flask app 'hello' (lazy loading)50     * Running on http://127.0.0.1:5000 (Press CTRL+C to quit)5152.. admonition:: Application Discovery Behavior5354    As a shortcut, if the file is named ``app.py`` or ``wsgi.py``, you55    don't have to use ``--app``. See :doc:`/cli` for more details.5657This launches a very simple builtin server, which is good enough for58testing but probably not what you want to use in production. For59deployment options see :doc:`deploying/index`.6061Now head over to http://127.0.0.1:5000/, and you should see your hello62world greeting.6364If another program is already using port 5000, you'll see65``OSError: [Errno 98]`` or ``OSError: [WinError 10013]`` when the66server tries to start. See :ref:`address-already-in-use` for how to67handle that.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.858687Debug Mode88----------8990The ``flask run`` command can do more than just start the development91server. By enabling debug mode, the server will automatically reload if92code changes, and will show an interactive debugger in the browser if an93error occurs during a request.9495.. image:: _static/debugger.png96    :align: center97    :class: screenshot98    :alt: The interactive debugger in action.99100.. warning::101102    The debugger allows executing arbitrary Python code from the103    browser. It is protected by a pin, but still represents a major104    security risk. Do not run the development server or debugger in a105    production environment.106107To enable all development features, set the ``--env`` option to108``development``.109110.. code-block:: text111112    $ flask --app hello --env development run113     * Serving Flask app 'hello' (lazy loading)114     * Environment: development115     * Debug mode: on116     * Running on http://127.0.0.1:5000 (Press CTRL+C to quit)117     * Restarting with stat118     * Debugger is active!119     * Debugger PIN: nnn-nnn-nnn120121See also:122123-   :doc:`/server` and :doc:`/cli` for information about running in124    development mode.125-   :doc:`/debugging` for information about using the built-in debugger126    and other debuggers.127-   :doc:`/logging` and :doc:`/errorhandling` to log errors and display128    nice error pages.129130131HTML Escaping132-------------133134When returning HTML (the default response type in Flask), any135user-provided values rendered in the output must be escaped to protect136from injection attacks. HTML templates rendered with Jinja, introduced137later, will do this automatically.138139:func:`~markupsafe.escape`, shown here, can be used manually. It is140omitted in most examples for brevity, but you should always be aware of141how you're using untrusted data.142143.. code-block:: python144145    from markupsafe import escape146147    @app.route("/<name>")148    def hello(name):149        return f"Hello, {escape(name)}!"150151If a user managed to submit the name ``<script>alert("bad")</script>``,152escaping causes it to be rendered as text, rather than running the153script in the user's browser.154155``<name>`` in the route captures a value from the URL and passes it to156the view function. These variable rules are explained below.157158159Routing160-------161162Modern web applications use meaningful URLs to help users. Users are more163likely to like a page and come back if the page uses a meaningful URL they can164remember and use to directly visit a page.165166Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. ::167168    @app.route('/')169    def index():170        return 'Index Page'171172    @app.route('/hello')173    def hello():174        return 'Hello, World'175176You can do more! You can make parts of the URL dynamic and attach multiple177rules to a function.178179Variable Rules180``````````````181182You can add variable sections to a URL by marking sections with183``<variable_name>``. Your function then receives the ``<variable_name>``184as a keyword argument. Optionally, you can use a converter to specify the type185of the argument like ``<converter:variable_name>``. ::186187    from markupsafe import escape188189    @app.route('/user/<username>')190    def show_user_profile(username):191        # show the user profile for that user192        return f'User {escape(username)}'193194    @app.route('/post/<int:post_id>')195    def show_post(post_id):196        # show the post with the given id, the id is an integer197        return f'Post {post_id}'198199    @app.route('/path/<path:subpath>')200    def show_subpath(subpath):201        # show the subpath after /path/202        return f'Subpath {escape(subpath)}'203204Converter types:205206========== ==========================================207``string`` (default) accepts any text without a slash208``int``    accepts positive integers209``float``  accepts positive floating point values210``path``   like ``string`` but also accepts slashes211``uuid``   accepts UUID strings212========== ==========================================213214215Unique URLs / Redirection Behavior216``````````````````````````````````217218The following two rules differ in their use of a trailing slash. ::219220    @app.route('/projects/')221    def projects():222        return 'The project page'223224    @app.route('/about')225    def about():226        return 'The about page'227228The canonical URL for the ``projects`` endpoint has a trailing slash.229It's similar to a folder in a file system. If you access the URL without230a trailing slash (``/projects``), Flask redirects you to the canonical URL231with the trailing slash (``/projects/``).232233The canonical URL for the ``about`` endpoint does not have a trailing234slash. It's similar to the pathname of a file. Accessing the URL with a235trailing slash (``/about/``) produces a 404 "Not Found" error. This helps236keep URLs unique for these resources, which helps search engines avoid237indexing the same page twice.238239240.. _url-building:241242URL Building243````````````244245To build a URL to a specific function, use the :func:`~flask.url_for` function.246It accepts the name of the function as its first argument and any number of247keyword arguments, each corresponding to a variable part of the URL rule.248Unknown variable parts are appended to the URL as query parameters.249250Why would you want to build URLs using the URL reversing function251:func:`~flask.url_for` instead of hard-coding them into your templates?2522531. Reversing is often more descriptive than hard-coding the URLs.2542. You can change your URLs in one go instead of needing to remember to255   manually change hard-coded URLs.2563. URL building handles escaping of special characters transparently.2574. The generated paths are always absolute, avoiding unexpected behavior258   of relative paths in browsers.2595. If your application is placed outside the URL root, for example, in260   ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly261   handles that for you.262263For example, here we use the :meth:`~flask.Flask.test_request_context` method264to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context`265tells Flask to behave as though it's handling a request even while we use a266Python shell. See :ref:`context-locals`.267268.. code-block:: python269270    from flask import url_for271272    @app.route('/')273    def index():274        return 'index'275276    @app.route('/login')277    def login():278        return 'login'279280    @app.route('/user/<username>')281    def profile(username):282        return f'{username}\'s profile'283284    with app.test_request_context():285        print(url_for('index'))286        print(url_for('login'))287        print(url_for('login', next='/'))288        print(url_for('profile', username='John Doe'))289290.. code-block:: text291292    /293    /login294    /login?next=/295    /user/John%20Doe296297298HTTP Methods299````````````300301Web applications use different HTTP methods when accessing URLs. You should302familiarize yourself with the HTTP methods as you work with Flask. By default,303a route only answers to ``GET`` requests. You can use the ``methods`` argument304of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods.305::306307    from flask import request308309    @app.route('/login', methods=['GET', 'POST'])310    def login():311        if request.method == 'POST':312            return do_the_login()313        else:314            return show_the_login_form()315316The example above keeps all methods for the route within one function,317which can be useful if each part uses some common data.318319You can also separate views for different methods into different320functions. Flask provides a shortcut for decorating such routes with321:meth:`~flask.Flask.get`, :meth:`~flask.Flask.post`, etc. for each322common HTTP method.323324.. code-block:: python325326    @app.get('/login')327    def login_get():328        return show_the_login_form()329330    @app.post('/login')331    def login_post():332        return do_the_login()333334If ``GET`` is present, Flask automatically adds support for the ``HEAD`` method335and handles ``HEAD`` requests according to the `HTTP RFC`_. Likewise,336``OPTIONS`` is automatically implemented for you.337338.. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt339340Static Files341------------342343Dynamic web applications also need static files.  That's usually where344the CSS and JavaScript files are coming from.  Ideally your web server is345configured to serve them for you, but during development Flask can do that346as well.  Just create a folder called :file:`static` in your package or next to347your module and it will be available at ``/static`` on the application.348349To generate URLs for static files, use the special ``'static'`` endpoint name::350351    url_for('static', filename='style.css')352353The file has to be stored on the filesystem as :file:`static/style.css`.354355Rendering Templates356-------------------357358Generating HTML from within Python is not fun, and actually pretty359cumbersome because you have to do the HTML escaping on your own to keep360the application secure.  Because of that Flask configures the `Jinja2361<https://palletsprojects.com/p/jinja/>`_ template engine for you automatically.362363To render a template you can use the :func:`~flask.render_template`364method.  All you have to do is provide the name of the template and the365variables you want to pass to the template engine as keyword arguments.366Here's a simple example of how to render a template::367368    from flask import render_template369370    @app.route('/hello/')371    @app.route('/hello/<name>')372    def hello(name=None):373        return render_template('hello.html', name=name)374375Flask will look for templates in the :file:`templates` folder.  So if your376application is a module, this folder is next to that module, if it's a377package it's actually inside your package:378379**Case 1**: a module::380381    /application.py382    /templates383        /hello.html384385**Case 2**: a package::386387    /application388        /__init__.py389        /templates390            /hello.html391392For templates you can use the full power of Jinja2 templates.  Head over393to the official `Jinja2 Template Documentation394<https://jinja.palletsprojects.com/templates/>`_ for more information.395396Here is an example template:397398.. sourcecode:: html+jinja399400    <!doctype html>401    <title>Hello from Flask</title>402    {% if name %}403      <h1>Hello {{ name }}!</h1>404    {% else %}405      <h1>Hello, World!</h1>406    {% endif %}407408Inside templates you also have access to the :data:`~flask.Flask.config`,409:class:`~flask.request`, :class:`~flask.session` and :class:`~flask.g` [#]_ objects410as well as the :func:`~flask.url_for` and :func:`~flask.get_flashed_messages` functions.411412Templates are especially useful if inheritance is used.  If you want to413know how that works, see :doc:`patterns/templateinheritance`. Basically414template inheritance makes it possible to keep certain elements on each415page (like header, navigation and footer).416417Automatic escaping is enabled, so if ``name`` contains HTML it will be escaped418automatically.  If you can trust a variable and you know that it will be419safe HTML (for example because it came from a module that converts wiki420markup to HTML) you can mark it as safe by using the421:class:`~markupsafe.Markup` class or by using the ``|safe`` filter in the422template.  Head over to the Jinja 2 documentation for more examples.423424Here is a basic introduction to how the :class:`~markupsafe.Markup` class works::425426    >>> from markupsafe import Markup427    >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'428    Markup('<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')429    >>> Markup.escape('<blink>hacker</blink>')430    Markup('&lt;blink&gt;hacker&lt;/blink&gt;')431    >>> Markup('<em>Marked up</em> &raquo; HTML').striptags()432    'Marked up » HTML'433434.. versionchanged:: 0.5435436   Autoescaping is no longer enabled for all templates.  The following437   extensions for templates trigger autoescaping: ``.html``, ``.htm``,438   ``.xml``, ``.xhtml``.  Templates loaded from a string will have439   autoescaping disabled.440441.. [#] Unsure what that :class:`~flask.g` object is? It's something in which442   you can store information for your own needs. See the documentation443   for :class:`flask.g` and :doc:`patterns/sqlite3`.444445446Accessing Request Data447----------------------448449For web applications it's crucial to react to the data a client sends to450the server.  In Flask this information is provided by the global451:class:`~flask.request` object.  If you have some experience with Python452you might be wondering how that object can be global and how Flask453manages to still be threadsafe.  The answer is context locals:454455456.. _context-locals:457458Context Locals459``````````````460461.. admonition:: Insider Information462463   If you want to understand how that works and how you can implement464   tests with context locals, read this section, otherwise just skip it.465466Certain objects in Flask are global objects, but not of the usual kind.467These objects are actually proxies to objects that are local to a specific468context.  What a mouthful.  But that is actually quite easy to understand.469470Imagine the context being the handling thread.  A request comes in and the471web server decides to spawn a new thread (or something else, the472underlying object is capable of dealing with concurrency systems other473than threads).  When Flask starts its internal request handling it474figures out that the current thread is the active context and binds the475current application and the WSGI environments to that context (thread).476It does that in an intelligent way so that one application can invoke another477application without breaking.478479So what does this mean to you?  Basically you can completely ignore that480this is the case unless you are doing something like unit testing.  You481will notice that code which depends on a request object will suddenly break482because there is no request object.  The solution is creating a request483object yourself and binding it to the context.  The easiest solution for484unit testing is to use the :meth:`~flask.Flask.test_request_context`485context manager.  In combination with the ``with`` statement it will bind a486test request so that you can interact with it.  Here is an example::487488    from flask import request489490    with app.test_request_context('/hello', method='POST'):491        # now you can do something with the request until the492        # end of the with block, such as basic assertions:493        assert request.path == '/hello'494        assert request.method == 'POST'495496The other possibility is passing a whole WSGI environment to the497:meth:`~flask.Flask.request_context` method::498499    with app.request_context(environ):500        assert request.method == 'POST'501502The Request Object503``````````````````504505The request object is documented in the API section and we will not cover506it here in detail (see :class:`~flask.Request`). Here is a broad overview of507some of the most common operations.  First of all you have to import it from508the ``flask`` module::509510    from flask import request511512The current request method is available by using the513:attr:`~flask.Request.method` attribute.  To access form data (data514transmitted in a ``POST`` or ``PUT`` request) you can use the515:attr:`~flask.Request.form` attribute.  Here is a full example of the two516attributes mentioned above::517518    @app.route('/login', methods=['POST', 'GET'])519    def login():520        error = None521        if request.method == 'POST':522            if valid_login(request.form['username'],523                           request.form['password']):524                return log_the_user_in(request.form['username'])525            else:526                error = 'Invalid username/password'527        # the code below is executed if the request method528        # was GET or the credentials were invalid529        return render_template('login.html', error=error)530531What happens if the key does not exist in the ``form`` attribute?  In that532case a special :exc:`KeyError` is raised.  You can catch it like a533standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request534error page is shown instead.  So for many situations you don't have to535deal with that problem.536537To access parameters submitted in the URL (``?key=value``) you can use the538:attr:`~flask.Request.args` attribute::539540    searchword = request.args.get('key', '')541542We recommend accessing URL parameters with `get` or by catching the543:exc:`KeyError` because users might change the URL and presenting them a 400544bad request page in that case is not user friendly.545546For a full list of methods and attributes of the request object, head over547to the :class:`~flask.Request` documentation.548549550File Uploads551````````````552553You can handle uploaded files with Flask easily.  Just make sure not to554forget to set the ``enctype="multipart/form-data"`` attribute on your HTML555form, otherwise the browser will not transmit your files at all.556557Uploaded files are stored in memory or at a temporary location on the558filesystem.  You can access those files by looking at the559:attr:`~flask.request.files` attribute on the request object.  Each560uploaded file is stored in that dictionary.  It behaves just like a561standard Python :class:`file` object, but it also has a562:meth:`~werkzeug.datastructures.FileStorage.save` method that563allows you to store that file on the filesystem of the server.564Here is a simple example showing how that works::565566    from flask import request567568    @app.route('/upload', methods=['GET', 'POST'])569    def upload_file():570        if request.method == 'POST':571            f = request.files['the_file']572            f.save('/var/www/uploads/uploaded_file.txt')573        ...574575If you want to know how the file was named on the client before it was576uploaded to your application, you can access the577:attr:`~werkzeug.datastructures.FileStorage.filename` attribute.578However please keep in mind that this value can be forged579so never ever trust that value.  If you want to use the filename580of the client to store the file on the server, pass it through the581:func:`~werkzeug.utils.secure_filename` function that582Werkzeug provides for you::583584    from werkzeug.utils import secure_filename585586    @app.route('/upload', methods=['GET', 'POST'])587    def upload_file():588        if request.method == 'POST':589            file = request.files['the_file']590            file.save(f"/var/www/uploads/{secure_filename(file.filename)}")591        ...592593For some better examples, see :doc:`patterns/fileuploads`.594595Cookies596```````597598To access cookies you can use the :attr:`~flask.Request.cookies`599attribute.  To set cookies you can use the600:attr:`~flask.Response.set_cookie` method of response objects.  The601:attr:`~flask.Request.cookies` attribute of request objects is a602dictionary with all the cookies the client transmits.  If you want to use603sessions, do not use the cookies directly but instead use the604:ref:`sessions` in Flask that add some security on top of cookies for you.605606Reading cookies::607608    from flask import request609610    @app.route('/')611    def index():612        username = request.cookies.get('username')613        # use cookies.get(key) instead of cookies[key] to not get a614        # KeyError if the cookie is missing.615616Storing cookies::617618    from flask import make_response619620    @app.route('/')621    def index():622        resp = make_response(render_template(...))623        resp.set_cookie('username', 'the username')624        return resp625626Note that cookies are set on response objects.  Since you normally627just return strings from the view functions Flask will convert them into628response objects for you.  If you explicitly want to do that you can use629the :meth:`~flask.make_response` function and then modify it.630631Sometimes you might want to set a cookie at a point where the response632object does not exist yet.  This is possible by utilizing the633:doc:`patterns/deferredcallbacks` pattern.634635For this also see :ref:`about-responses`.636637Redirects and Errors638--------------------639640To redirect a user to another endpoint, use the :func:`~flask.redirect`641function; to abort a request early with an error code, use the642:func:`~flask.abort` function::643644    from flask import abort, redirect, url_for645646    @app.route('/')647    def index():648        return redirect(url_for('login'))649650    @app.route('/login')651    def login():652        abort(401)653        this_is_never_executed()654655This is a rather pointless example because a user will be redirected from656the index to a page they cannot access (401 means access denied) but it657shows how that works.658659By default a black and white error page is shown for each error code.  If660you want to customize the error page, you can use the661:meth:`~flask.Flask.errorhandler` decorator::662663    from flask import render_template664665    @app.errorhandler(404)666    def page_not_found(error):667        return render_template('page_not_found.html'), 404668669Note the ``404`` after the :func:`~flask.render_template` call.  This670tells Flask that the status code of that page should be 404 which means671not found.  By default 200 is assumed which translates to: all went well.672673See :doc:`errorhandling` for more details.674675.. _about-responses:676677About Responses678---------------679680The return value from a view function is automatically converted into681a response object for you. If the return value is a string it's682converted into a response object with the string as response body, a683``200 OK`` status code and a :mimetype:`text/html` mimetype. If the684return value is a dict, :func:`jsonify` is called to produce a response.685The logic that Flask applies to converting return values into response686objects is as follows:6876881.  If a response object of the correct type is returned it's directly689    returned from the view.6902.  If it's a string, a response object is created with that data and691    the default parameters.6923.  If it's a dict, a response object is created using ``jsonify``.6934.  If a tuple is returned the items in the tuple can provide extra694    information. Such tuples have to be in the form695    ``(response, status)``, ``(response, headers)``, or696    ``(response, status, headers)``. The ``status`` value will override697    the status code and ``headers`` can be a list or dictionary of698    additional header values.6995.  If none of that works, Flask will assume the return value is a700    valid WSGI application and convert that into a response object.701702If you want to get hold of the resulting response object inside the view703you can use the :func:`~flask.make_response` function.704705Imagine you have a view like this::706707    from flask import render_template708709    @app.errorhandler(404)710    def not_found(error):711        return render_template('error.html'), 404712713You just need to wrap the return expression with714:func:`~flask.make_response` and get the response object to modify it, then715return it::716717    from flask import make_response718719    @app.errorhandler(404)720    def not_found(error):721        resp = make_response(render_template('error.html'), 404)722        resp.headers['X-Something'] = 'A value'723        return resp724725726APIs with JSON727``````````````728729A common response format when writing an API is JSON. It's easy to get730started writing such an API with Flask. If you return a ``dict`` from a731view, it will be converted to a JSON response.732733.. code-block:: python734735    @app.route("/me")736    def me_api():737        user = get_current_user()738        return {739            "username": user.username,740            "theme": user.theme,741            "image": url_for("user_image", filename=user.image),742        }743744Depending on your API design, you may want to create JSON responses for745types other than ``dict``. In that case, use the746:func:`~flask.json.jsonify` function, which will serialize any supported747JSON data type. Or look into Flask community extensions that support748more complex applications.749750.. code-block:: python751752    from flask import jsonify753754    @app.route("/users")755    def users_api():756        users = get_all_users()757        return jsonify([user.to_json() for user in users])758759760.. _sessions:761762Sessions763--------764765In addition to the request object there is also a second object called766:class:`~flask.session` which allows you to store information specific to a767user from one request to the next.  This is implemented on top of cookies768for you and signs the cookies cryptographically.  What this means is that769the user could look at the contents of your cookie but not modify it,770unless they know the secret key used for signing.771772In order to use sessions you have to set a secret key.  Here is how773sessions work::774775    from flask import session776777    # Set the secret key to some random bytes. Keep this really secret!778    app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'779780    @app.route('/')781    def index():782        if 'username' in session:783            return f'Logged in as {session["username"]}'784        return 'You are not logged in'785786    @app.route('/login', methods=['GET', 'POST'])787    def login():788        if request.method == 'POST':789            session['username'] = request.form['username']790            return redirect(url_for('index'))791        return '''792            <form method="post">793                <p><input type=text name=username>794                <p><input type=submit value=Login>795            </form>796        '''797798    @app.route('/logout')799    def logout():800        # remove the username from the session if it's there801        session.pop('username', None)802        return redirect(url_for('index'))803804.. admonition:: How to generate good secret keys805806    A secret key should be as random as possible. Your operating system has807    ways to generate pretty random data based on a cryptographic random808    generator. Use the following command to quickly generate a value for809    :attr:`Flask.secret_key` (or :data:`SECRET_KEY`)::810811        $ python -c 'import secrets; print(secrets.token_hex())'812        '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'813814A note on cookie-based sessions: Flask will take the values you put into the815session object and serialize them into a cookie.  If you are finding some816values do not persist across requests, cookies are indeed enabled, and you are817not getting a clear error message, check the size of the cookie in your page818responses compared to the size supported by web browsers.819820Besides the default client-side based sessions, if you want to handle821sessions on the server-side instead, there are several822Flask extensions that support this.823824Message Flashing825----------------826827Good applications and user interfaces are all about feedback.  If the user828does not get enough feedback they will probably end up hating the829application.  Flask provides a really simple way to give feedback to a830user with the flashing system.  The flashing system basically makes it831possible to record a message at the end of a request and access it on the next832(and only the next) request.  This is usually combined with a layout833template to expose the message.834835To flash a message use the :func:`~flask.flash` method, to get hold of the836messages you can use :func:`~flask.get_flashed_messages` which is also837available in the templates. See :doc:`patterns/flashing` for a full838example.839840Logging841-------842843.. versionadded:: 0.3844845Sometimes you might be in a situation where you deal with data that846should be correct, but actually is not.  For example you may have847some client-side code that sends an HTTP request to the server848but it's obviously malformed.  This might be caused by a user tampering849with the data, or the client code failing.  Most of the time it's okay850to reply with ``400 Bad Request`` in that situation, but sometimes851that won't do and the code has to continue working.852853You may still want to log that something fishy happened.  This is where854loggers come in handy.  As of Flask 0.3 a logger is preconfigured for you855to use.856857Here are some example log calls::858859    app.logger.debug('A value for debugging')860    app.logger.warning('A warning occurred (%d apples)', 42)861    app.logger.error('An error occurred')862863The attached :attr:`~flask.Flask.logger` is a standard logging864:class:`~logging.Logger`, so head over to the official :mod:`logging`865docs for more information.866867See :doc:`errorhandling`.868869870Hooking in WSGI Middleware871--------------------------872873To add WSGI middleware to your Flask application, wrap the application's874``wsgi_app`` attribute. For example, to apply Werkzeug's875:class:`~werkzeug.middleware.proxy_fix.ProxyFix` middleware for running876behind Nginx:877878.. code-block:: python879880    from werkzeug.middleware.proxy_fix import ProxyFix881    app.wsgi_app = ProxyFix(app.wsgi_app)882883Wrapping ``app.wsgi_app`` instead of ``app`` means that ``app`` still884points at your Flask application, not at the middleware, so you can885continue to use and configure ``app`` directly.886887Using Flask Extensions888----------------------889890Extensions are packages that help you accomplish common tasks. For891example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple892and easy to use with Flask.893894For more on Flask extensions, see :doc:`extensions`.895896Deploying to a Web Server897-------------------------898899Ready to deploy your new Flask app? See :doc:`deploying/index`.