Skip to content
Myr

quickstart.rst

This file

Path

docs/quickstart.rst

894 lines · 31.4 KiB

Last changed by

Merge pull request #3111 from pgjones/masterDavid Lordbefore adoption855d59b

History of this file

Take it

1.. _quickstart:23Quickstart4==========56Eager to get started?  This page gives a good introduction to Flask.  It7assumes you already have Flask installed.  If you do not, head over to the8:ref:`installation` section.91011A Minimal Application12---------------------1314A minimal Flask application looks something like this::1516    from flask import Flask17    app = Flask(__name__)1819    @app.route('/')20    def hello_world():21        return 'Hello, World!'2223So what did that code do?24251. First we imported the :class:`~flask.Flask` class.  An instance of this26   class will be our WSGI application.272. Next we create an instance of this class. The first argument is the name of28   the application's module or package.  If you are using a single module (as29   in this example), you should use ``__name__`` because depending on if it's30   started as application or imported as module the name will be different31   (``'__main__'`` versus the actual import name). This is needed so that32   Flask knows where to look for templates, static files, and so on. For more33   information have a look at the :class:`~flask.Flask` documentation.343. We then use the :meth:`~flask.Flask.route` decorator to tell Flask what URL35   should trigger our function.364. The function is given a name which is also used to generate URLs for that37   particular function, and returns the message we want to display in the38   user's browser.3940Just save it as :file:`hello.py` or something similar. Make sure to not call41your application :file:`flask.py` because this would conflict with Flask42itself.4344To run the application you can either use the :command:`flask` command or45python's ``-m`` switch with Flask.  Before you can do that you need46to tell your terminal the application to work with by exporting the47``FLASK_APP`` environment variable::4849    $ 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"6162Alternatively you can use :command:`python -m flask`::6364    $ export FLASK_APP=hello.py65    $ python -m flask run66     * Running on http://127.0.0.1:5000/6768This launches a very simple builtin server, which is good enough for testing69but probably not what you want to use in production. For deployment options see70:ref:`deployment`.7172Now head over to `http://127.0.0.1:5000/ <http://127.0.0.1:5000/>`_, and you73should see your hello world greeting.7475.. _public-server:7677.. admonition:: Externally Visible Server7879   If you run the server you will notice that the server is only accessible80   from your own computer, not from any other in the network.  This is the81   default because in debugging mode a user of the application can execute82   arbitrary Python code on your computer.8384   If you have the debugger disabled or trust the users on your network,85   you can make the server publicly available simply by adding86   ``--host=0.0.0.0`` to the command line::8788       $ flask run --host=0.0.0.08990   This tells your operating system to listen on all public IPs.919293What to do if the Server does not Start94---------------------------------------9596In case the :command:`python -m flask` fails or :command:`flask`97does not exist, there are multiple reasons this might be the case.98First of all you need to look at the error message.99100Old Version of Flask101````````````````````102103Versions of Flask older than 0.11 use to have different ways to start the104application.  In short, the :command:`flask` command did not exist, and105neither did :command:`python -m flask`.  In that case you have two options:106either upgrade to newer Flask versions or have a look at the :ref:`server`107docs to see the alternative method for running a server.108109Invalid Import Name110```````````````````111112The ``FLASK_APP`` environment variable is the name of the module to import at113:command:`flask run`. In case that module is incorrectly named you will get an114import error upon start (or if debug is enabled when you navigate to the115application). It will tell you what it tried to import and why it failed.116117The most common reason is a typo or because you did not actually create an118``app`` object.119120.. _debug-mode:121122Debug Mode123----------124125(Want to just log errors and stack traces? See :ref:`application-errors`)126127The :command:`flask` script is nice to start a local development server, but128you would have to restart it manually after each change to your code.129That is not very nice and Flask can do better.  If you enable debug130support the server will reload itself on code changes, and it will also131provide you with a helpful debugger if things go wrong.132133To enable all development features (including debug mode) you can export134the ``FLASK_ENV`` environment variable and set it to ``development``135before running the server::136137    $ export FLASK_ENV=development138    $ flask run139140(On Windows you need to use ``set`` instead of ``export``.)141142This does the following things:1431441.  it activates the debugger1452.  it activates the automatic reloader1463.  it enables the debug mode on the Flask application.147148You can also control debug mode separately from the environment by149exporting ``FLASK_DEBUG=1``.150151There are more parameters that are explained in the :ref:`server` docs.152153.. admonition:: Attention154155   Even though the interactive debugger does not work in forking environments156   (which makes it nearly impossible to use on production servers), it still157   allows the execution of arbitrary code. This makes it a major security risk158   and therefore it **must never be used on production machines**.159160Screenshot of the debugger in action:161162.. image:: _static/debugger.png163   :align: center164   :class: screenshot165   :alt: screenshot of debugger in action166167More information on using the debugger can be found in the `Werkzeug168documentation`_.169170.. _Werkzeug documentation: http://werkzeug.pocoo.org/docs/debug/#using-the-debugger171172Have another debugger in mind? See :ref:`working-with-debuggers`.173174175Routing176-------177178Modern web applications use meaningful URLs to help users. Users are more179likely to like a page and come back if the page uses a meaningful URL they can180remember and use to directly visit a page.181182Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. ::183184    @app.route('/')185    def index():186        return 'Index Page'187188    @app.route('/hello')189    def hello():190        return 'Hello, World'191192You can do more! You can make parts of the URL dynamic and attach multiple193rules to a function.194195Variable Rules196``````````````197198You can add variable sections to a URL by marking sections with199``<variable_name>``. Your function then receives the ``<variable_name>``200as a keyword argument. Optionally, you can use a converter to specify the type201of the argument like ``<converter:variable_name>``. ::202203    @app.route('/user/<username>')204    def show_user_profile(username):205        # show the user profile for that user206        return 'User %s' % escape(username)207208    @app.route('/post/<int:post_id>')209    def show_post(post_id):210        # show the post with the given id, the id is an integer211        return 'Post %d' % post_id212213    @app.route('/path/<path:subpath>')214    def show_subpath(subpath):215        # show the subpath after /path/216        return 'Subpath %s' % escape(subpath)217218Converter types:219220========== ==========================================221``string`` (default) accepts any text without a slash222``int``    accepts positive integers223``float``  accepts positive floating point values224``path``   like ``string`` but also accepts slashes225``uuid``   accepts UUID strings226========== ==========================================227228Unique URLs / Redirection Behavior229``````````````````````````````````230231The following two rules differ in their use of a trailing slash. ::232233    @app.route('/projects/')234    def projects():235        return 'The project page'236237    @app.route('/about')238    def about():239        return 'The about page'240241The canonical URL for the ``projects`` endpoint has a trailing slash.242It's similar to a folder in a file system. If you access the URL without243a trailing slash, Flask redirects you to the canonical URL with the244trailing slash.245246The canonical URL for the ``about`` endpoint does not have a trailing247slash. It's similar to the pathname of a file. Accessing the URL with a248trailing slash produces a 404 "Not Found" error. This helps keep URLs249unique for these resources, which helps search engines avoid indexing250the same page twice.251252253.. _url-building:254255URL Building256````````````257258To build a URL to a specific function, use the :func:`~flask.url_for` function.259It accepts the name of the function as its first argument and any number of260keyword arguments, each corresponding to a variable part of the URL rule.261Unknown variable parts are appended to the URL as query parameters.262263Why would you want to build URLs using the URL reversing function264:func:`~flask.url_for` instead of hard-coding them into your templates?2652661. Reversing is often more descriptive than hard-coding the URLs.2672. You can change your URLs in one go instead of needing to remember to268   manually change hard-coded URLs.2693. URL building handles escaping of special characters and Unicode data270   transparently.2714. The generated paths are always absolute, avoiding unexpected behavior272   of relative paths in browsers.2735. If your application is placed outside the URL root, for example, in274   ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly275   handles that for you.276277For example, here we use the :meth:`~flask.Flask.test_request_context` method278to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context`279tells Flask to behave as though it's handling a request even while we use a280Python shell. See :ref:`context-locals`.281282.. code-block:: python283284    from flask import Flask, escape, url_for285286    app = Flask(__name__)287288    @app.route('/')289    def index():290        return 'index'291292    @app.route('/login')293    def login():294        return 'login'295296    @app.route('/user/<username>')297    def profile(username):298        return '{}\'s profile'.format(escape(username))299300    with app.test_request_context():301        print(url_for('index'))302        print(url_for('login'))303        print(url_for('login', next='/'))304        print(url_for('profile', username='John Doe'))305306.. code-block:: text307308    /309    /login310    /login?next=/311    /user/John%20Doe312313314HTTP Methods315````````````316317Web applications use different HTTP methods when accessing URLs. You should318familiarize yourself with the HTTP methods as you work with Flask. By default,319a route only answers to ``GET`` requests. You can use the ``methods`` argument320of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods.321::322323    from flask import request324325    @app.route('/login', methods=['GET', 'POST'])326    def login():327        if request.method == 'POST':328            return do_the_login()329        else:330            return show_the_login_form()331332If ``GET`` is present, Flask automatically adds support for the ``HEAD`` method333and handles ``HEAD`` requests according to the `HTTP RFC`_. Likewise,334``OPTIONS`` is automatically implemented for you.335336.. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt337338Static Files339------------340341Dynamic web applications also need static files.  That's usually where342the CSS and JavaScript files are coming from.  Ideally your web server is343configured to serve them for you, but during development Flask can do that344as well.  Just create a folder called :file:`static` in your package or next to345your module and it will be available at ``/static`` on the application.346347To generate URLs for static files, use the special ``'static'`` endpoint name::348349    url_for('static', filename='style.css')350351The file has to be stored on the filesystem as :file:`static/style.css`.352353Rendering Templates354-------------------355356Generating HTML from within Python is not fun, and actually pretty357cumbersome because you have to do the HTML escaping on your own to keep358the application secure.  Because of that Flask configures the `Jinja2359<http://jinja.pocoo.org/>`_ template engine for you automatically.360361To render a template you can use the :func:`~flask.render_template`362method.  All you have to do is provide the name of the template and the363variables you want to pass to the template engine as keyword arguments.364Here's a simple example of how to render a template::365366    from flask import render_template367368    @app.route('/hello/')369    @app.route('/hello/<name>')370    def hello(name=None):371        return render_template('hello.html', name=name)372373Flask will look for templates in the :file:`templates` folder.  So if your374application is a module, this folder is next to that module, if it's a375package it's actually inside your package:376377**Case 1**: a module::378379    /application.py380    /templates381        /hello.html382383**Case 2**: a package::384385    /application386        /__init__.py387        /templates388            /hello.html389390For templates you can use the full power of Jinja2 templates.  Head over391to the official `Jinja2 Template Documentation392<http://jinja.pocoo.org/docs/templates>`_ for more information.393394Here is an example template:395396.. sourcecode:: html+jinja397398    <!doctype html>399    <title>Hello from Flask</title>400    {% if name %}401      <h1>Hello {{ name }}!</h1>402    {% else %}403      <h1>Hello, World!</h1>404    {% endif %}405406Inside templates you also have access to the :class:`~flask.request`,407:class:`~flask.session` and :class:`~flask.g` [#]_ objects408as well as the :func:`~flask.get_flashed_messages` function.409410Templates are especially useful if inheritance is used.  If you want to411know how that works, head over to the :ref:`template-inheritance` pattern412documentation.  Basically template inheritance makes it possible to keep413certain elements on each page (like header, navigation and footer).414415Automatic escaping is enabled, so if ``name`` contains HTML it will be escaped416automatically.  If you can trust a variable and you know that it will be417safe HTML (for example because it came from a module that converts wiki418markup to HTML) you can mark it as safe by using the419:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the420template.  Head over to the Jinja 2 documentation for more examples.421422Here is a basic introduction to how the :class:`~jinja2.Markup` class works::423424    >>> from flask import Markup425    >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'426    Markup(u'<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')427    >>> Markup.escape('<blink>hacker</blink>')428    Markup(u'&lt;blink&gt;hacker&lt;/blink&gt;')429    >>> Markup('<em>Marked up</em> &raquo; HTML').striptags()430    u'Marked up \xbb HTML'431432.. versionchanged:: 0.5433434   Autoescaping is no longer enabled for all templates.  The following435   extensions for templates trigger autoescaping: ``.html``, ``.htm``,436   ``.xml``, ``.xhtml``.  Templates loaded from a string will have437   autoescaping disabled.438439.. [#] Unsure what that :class:`~flask.g` object is? It's something in which440   you can store information for your own needs, check the documentation of441   that object (:class:`~flask.g`) and the :ref:`sqlite3` for more442   information.443444445Accessing Request Data446----------------------447448For web applications it's crucial to react to the data a client sends to449the server.  In Flask this information is provided by the global450:class:`~flask.request` object.  If you have some experience with Python451you might be wondering how that object can be global and how Flask452manages to still be threadsafe.  The answer is context locals:453454455.. _context-locals:456457Context Locals458``````````````459460.. admonition:: Insider Information461462   If you want to understand how that works and how you can implement463   tests with context locals, read this section, otherwise just skip it.464465Certain objects in Flask are global objects, but not of the usual kind.466These objects are actually proxies to objects that are local to a specific467context.  What a mouthful.  But that is actually quite easy to understand.468469Imagine the context being the handling thread.  A request comes in and the470web server decides to spawn a new thread (or something else, the471underlying object is capable of dealing with concurrency systems other472than threads).  When Flask starts its internal request handling it473figures out that the current thread is the active context and binds the474current application and the WSGI environments to that context (thread).475It does that in an intelligent way so that one application can invoke another476application without breaking.477478So what does this mean to you?  Basically you can completely ignore that479this is the case unless you are doing something like unit testing.  You480will notice that code which depends on a request object will suddenly break481because there is no request object.  The solution is creating a request482object yourself and binding it to the context.  The easiest solution for483unit testing is to use the :meth:`~flask.Flask.test_request_context`484context manager.  In combination with the ``with`` statement it will bind a485test request so that you can interact with it.  Here is an example::486487    from flask import request488489    with app.test_request_context('/hello', method='POST'):490        # now you can do something with the request until the491        # end of the with block, such as basic assertions:492        assert request.path == '/hello'493        assert request.method == 'POST'494495The other possibility is passing a whole WSGI environment to the496:meth:`~flask.Flask.request_context` method::497498    from flask import request499500    with app.request_context(environ):501        assert request.method == 'POST'502503The Request Object504``````````````````505506The request object is documented in the API section and we will not cover507it here in detail (see :class:`~flask.Request`). Here is a broad overview of508some of the most common operations.  First of all you have to import it from509the ``flask`` module::510511    from flask import request512513The current request method is available by using the514:attr:`~flask.Request.method` attribute.  To access form data (data515transmitted in a ``POST`` or ``PUT`` request) you can use the516:attr:`~flask.Request.form` attribute.  Here is a full example of the two517attributes mentioned above::518519    @app.route('/login', methods=['POST', 'GET'])520    def login():521        error = None522        if request.method == 'POST':523            if valid_login(request.form['username'],524                           request.form['password']):525                return log_the_user_in(request.form['username'])526            else:527                error = 'Invalid username/password'528        # the code below is executed if the request method529        # was GET or the credentials were invalid530        return render_template('login.html', error=error)531532What happens if the key does not exist in the ``form`` attribute?  In that533case a special :exc:`KeyError` is raised.  You can catch it like a534standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request535error page is shown instead.  So for many situations you don't have to536deal with that problem.537538To access parameters submitted in the URL (``?key=value``) you can use the539:attr:`~flask.Request.args` attribute::540541    searchword = request.args.get('key', '')542543We recommend accessing URL parameters with `get` or by catching the544:exc:`KeyError` because users might change the URL and presenting them a 400545bad request page in that case is not user friendly.546547For a full list of methods and attributes of the request object, head over548to the :class:`~flask.Request` documentation.549550551File Uploads552````````````553554You can handle uploaded files with Flask easily.  Just make sure not to555forget to set the ``enctype="multipart/form-data"`` attribute on your HTML556form, otherwise the browser will not transmit your files at all.557558Uploaded files are stored in memory or at a temporary location on the559filesystem.  You can access those files by looking at the560:attr:`~flask.request.files` attribute on the request object.  Each561uploaded file is stored in that dictionary.  It behaves just like a562standard Python :class:`file` object, but it also has a563:meth:`~werkzeug.datastructures.FileStorage.save` method that564allows you to store that file on the filesystem of the server.565Here is a simple example showing how that works::566567    from flask import request568569    @app.route('/upload', methods=['GET', 'POST'])570    def upload_file():571        if request.method == 'POST':572            f = request.files['the_file']573            f.save('/var/www/uploads/uploaded_file.txt')574        ...575576If you want to know how the file was named on the client before it was577uploaded to your application, you can access the578:attr:`~werkzeug.datastructures.FileStorage.filename` attribute.579However please keep in mind that this value can be forged580so never ever trust that value.  If you want to use the filename581of the client to store the file on the server, pass it through the582:func:`~werkzeug.utils.secure_filename` function that583Werkzeug provides for you::584585    from flask import request586    from werkzeug.utils import secure_filename587588    @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/' + secure_filename(f.filename))593        ...594595For some better examples, checkout the :ref:`uploading-files` pattern.596597Cookies598```````599600To access cookies you can use the :attr:`~flask.Request.cookies`601attribute.  To set cookies you can use the602:attr:`~flask.Response.set_cookie` method of response objects.  The603:attr:`~flask.Request.cookies` attribute of request objects is a604dictionary with all the cookies the client transmits.  If you want to use605sessions, do not use the cookies directly but instead use the606:ref:`sessions` in Flask that add some security on top of cookies for you.607608Reading cookies::609610    from flask import request611612    @app.route('/')613    def index():614        username = request.cookies.get('username')615        # use cookies.get(key) instead of cookies[key] to not get a616        # KeyError if the cookie is missing.617618Storing cookies::619620    from flask import make_response621622    @app.route('/')623    def index():624        resp = make_response(render_template(...))625        resp.set_cookie('username', 'the username')626        return resp627628Note that cookies are set on response objects.  Since you normally629just return strings from the view functions Flask will convert them into630response objects for you.  If you explicitly want to do that you can use631the :meth:`~flask.make_response` function and then modify it.632633Sometimes you might want to set a cookie at a point where the response634object does not exist yet.  This is possible by utilizing the635:ref:`deferred-callbacks` pattern.636637For this also see :ref:`about-responses`.638639Redirects and Errors640--------------------641642To redirect a user to another endpoint, use the :func:`~flask.redirect`643function; to abort a request early with an error code, use the644:func:`~flask.abort` function::645646    from flask import abort, redirect, url_for647648    @app.route('/')649    def index():650        return redirect(url_for('login'))651652    @app.route('/login')653    def login():654        abort(401)655        this_is_never_executed()656657This is a rather pointless example because a user will be redirected from658the index to a page they cannot access (401 means access denied) but it659shows how that works.660661By default a black and white error page is shown for each error code.  If662you want to customize the error page, you can use the663:meth:`~flask.Flask.errorhandler` decorator::664665    from flask import render_template666667    @app.errorhandler(404)668    def page_not_found(error):669        return render_template('page_not_found.html'), 404670671Note the ``404`` after the :func:`~flask.render_template` call.  This672tells Flask that the status code of that page should be 404 which means673not found.  By default 200 is assumed which translates to: all went well.674675See :ref:`error-handlers` for more details.676677.. _about-responses:678679About Responses680---------------681682The return value from a view function is automatically converted into683a response object for you. If the return value is a string it's684converted into a response object with the string as response body, a685``200 OK`` status code and a :mimetype:`text/html` mimetype. If the686return value is a dict, :func:`jsonify` is called to produce a response.687The logic that Flask applies to converting return values into response688objects is as follows:6896901.  If a response object of the correct type is returned it's directly691    returned from the view.6922.  If it's a string, a response object is created with that data and693    the default parameters.6943.  If it's a dict, a response object is created using ``jsonify``.6954.  If a tuple is returned the items in the tuple can provide extra696    information. Such tuples have to be in the form697    ``(response, status)``, ``(response, headers)``, or698    ``(response, status, headers)``. The ``status`` value will override699    the status code and ``headers`` can be a list or dictionary of700    additional header values.7015.  If none of that works, Flask will assume the return value is a702    valid WSGI application and convert that into a response object.703704If you want to get hold of the resulting response object inside the view705you can use the :func:`~flask.make_response` function.706707Imagine you have a view like this::708709    @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    @app.errorhandler(404)718    def not_found(error):719        resp = make_response(render_template('error.html'), 404)720        resp.headers['X-Something'] = 'A value'721        return resp722723724APIs with JSON725``````````````726727A common response format when writing an API is JSON. It's easy to get728started writing such an API with Flask. If you return a ``dict`` from a729view, it will be converted to a JSON response.730731.. code-block:: python732733    @app.route("/me")734    def me_api():735        user = get_current_user()736        return {737            "username": user.username,738            "theme": user.theme,739            "image": url_for("user_image", filename=user.image),740        }741742Depending on your API design, you may want to create JSON responses for743types other than ``dict``. In that case, use the744:func:`~flask.json.jsonify` function, which will serialize any supported745JSON data type. Or look into Flask community extensions that support746more complex applications.747748.. code-block:: python749750    @app.route("/users")751    def users_api():752        users = get_all_users()753        return jsonify([user.to_json() for user in users])754755756.. _sessions:757758Sessions759--------760761In addition to the request object there is also a second object called762:class:`~flask.session` which allows you to store information specific to a763user from one request to the next.  This is implemented on top of cookies764for you and signs the cookies cryptographically.  What this means is that765the user could look at the contents of your cookie but not modify it,766unless they know the secret key used for signing.767768In order to use sessions you have to set a secret key.  Here is how769sessions work::770771    from flask import Flask, session, redirect, url_for, escape, request772773    app = Flask(__name__)774775    # Set the secret key to some random bytes. Keep this really secret!776    app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'777778    @app.route('/')779    def index():780        if 'username' in session:781            return 'Logged in as %s' % escape(session['username'])782        return 'You are not logged in'783784    @app.route('/login', methods=['GET', 'POST'])785    def login():786        if request.method == 'POST':787            session['username'] = request.form['username']788            return redirect(url_for('index'))789        return '''790            <form method="post">791                <p><input type=text name=username>792                <p><input type=submit value=Login>793            </form>794        '''795796    @app.route('/logout')797    def logout():798        # remove the username from the session if it's there799        session.pop('username', None)800        return redirect(url_for('index'))801802The :func:`~flask.escape` mentioned here does escaping for you if you are803not using the template engine (as in this example).804805.. admonition:: How to generate good secret keys806807    A secret key should be as random as possible. Your operating system has808    ways to generate pretty random data based on a cryptographic random809    generator. Use the following command to quickly generate a value for810    :attr:`Flask.secret_key` (or :data:`SECRET_KEY`)::811812        $ python -c 'import os; print(os.urandom(16))'813        b'_5#y2L"F4Q8z\n\xec]/'814815A note on cookie-based sessions: Flask will take the values you put into the816session object and serialize them into a cookie.  If you are finding some817values do not persist across requests, cookies are indeed enabled, and you are818not getting a clear error message, check the size of the cookie in your page819responses compared to the size supported by web browsers.820821Besides the default client-side based sessions, if you want to handle822sessions on the server-side instead, there are several823Flask extensions that support this.824825Message Flashing826----------------827828Good applications and user interfaces are all about feedback.  If the user829does not get enough feedback they will probably end up hating the830application.  Flask provides a really simple way to give feedback to a831user with the flashing system.  The flashing system basically makes it832possible to record a message at the end of a request and access it on the next833(and only the next) request.  This is usually combined with a layout834template to expose the message.835836To flash a message use the :func:`~flask.flash` method, to get hold of the837messages you can use :func:`~flask.get_flashed_messages` which is also838available in the templates.  Check out the :ref:`message-flashing-pattern`839for a full example.840841Logging842-------843844.. versionadded:: 0.3845846Sometimes you might be in a situation where you deal with data that847should be correct, but actually is not.  For example you may have848some client-side code that sends an HTTP request to the server849but it's obviously malformed.  This might be caused by a user tampering850with the data, or the client code failing.  Most of the time it's okay851to reply with ``400 Bad Request`` in that situation, but sometimes852that won't do and the code has to continue working.853854You may still want to log that something fishy happened.  This is where855loggers come in handy.  As of Flask 0.3 a logger is preconfigured for you856to use.857858Here are some example log calls::859860    app.logger.debug('A value for debugging')861    app.logger.warning('A warning occurred (%d apples)', 42)862    app.logger.error('An error occurred')863864The attached :attr:`~flask.Flask.logger` is a standard logging865:class:`~logging.Logger`, so head over to the official `logging866documentation <https://docs.python.org/library/logging.html>`_ for more867information.868869Read more on :ref:`application-errors`.870871Hooking in WSGI Middlewares872---------------------------873874If you want to add a WSGI middleware to your application you can wrap the875internal WSGI application.  For example if you want to use one of the876middlewares from the Werkzeug package to work around bugs in lighttpd, you877can do it like this::878879    from werkzeug.contrib.fixers import LighttpdCGIRootFix880    app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)881882Using Flask Extensions883----------------------884885Extensions are packages that help you accomplish common tasks. For886example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple887and easy to use with Flask.888889For more on Flask extensions, have a look at :ref:`extensions`.890891Deploying to a Web Server892-------------------------893894Ready to deploy your new Flask app? Go to :ref:`deployment`.