Skip to content
Myr

quickstart.rst

This file

Path

docs/quickstart.rst

855 lines · 31.2 KiB

Last changed by

Documentation on how to use external debuggers like eclipse/aptanaSundar Ramanbefore adoption9469260

History of this file

Take it

1.. _quickstart:23Quickstart4==========56Eager to get started?  This page gives a good introduction on how to get7started with Flask.  This assumes you already have Flask installed.  If8you do not, head over to the :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!'2223    if __name__ == '__main__':24        app.run()2526Just save it as `hello.py` or something similar and run it with your27Python interpreter.  Make sure to not call your application `flask.py`28because this would conflict with Flask itself.2930::3132    $ python hello.py33     * Running on http://127.0.0.1:5000/3435Head over to `http://127.0.0.1:5000/ <http://127.0.0.1:5000/>`_, you should36see your hello world greeting.3738So what did that code do?39401. First we imported the :class:`~flask.Flask` class.  An instance of this41   class will be our WSGI application.  The first argument is the name of42   the application's module.  If you are using a single module (as in this example)43   you should use `__name__` because depending on whether it's started as44   application or imported as module the name will be different45   (``'__main__'`` versus the actual import name).  For more information46   on this technique, have a look at the :class:`~flask.Flask` documentation.472. Next we create an instance of it.  We pass it the name of the module /48   package.  This is needed so that Flask knows where it should look for49   templates, static files and so on.503. Then we use the :meth:`~flask.Flask.route` decorator to tell Flask51   which URL should trigger our function.524. The function then has a name which is also used to generate URLs to53   that particular function, and returns the message we want to display in54   the user's browser.555. Finally we use the :meth:`~flask.Flask.run` function to run the56   local server with our application.  The ``if __name__ == '__main__':``57   makes sure the server only runs if the script is executed directly from58   the Python interpreter and not used as imported module.5960To stop the server, hit control-C.6162.. _public-server:6364.. admonition:: Externally Visible Server6566   If you run the server you will notice that the server is only accessible67   from your own computer, not from any other in the network.  This is the68   default because in debugging mode a user of the application can execute69   arbitrary Python code on your computer.7071   If you have `debug` disabled or trust the users on your network, you can72   make the server publicly available simply by changing the call of the73   :meth:`~flask.Flask.run` method to look like this::7475       app.run(host='0.0.0.0')7677   This tells your operating system to listen on a public IP.787980Debug Mode81----------8283The :meth:`~flask.Flask.run` method is nice to start a local84development server, but you would have to restart it manually after each85change to your code.  That is not very nice and Flask can do better.  If86you enable debug support the server will reload itself on code changes,87and it will also provide you with a helpful debugger if things go wrong.8889There are two ways to enable debugging.  Either set that flag on the90application object::9192    app.debug = True93    app.run()9495Or pass it to `run`::9697    app.run(debug=True)9899Both will have exactly the same effect.100101.. admonition:: Attention102103   Even though the interactive debugger does not work in forking environments104   (which makes it nearly impossible to use on production servers), it still105   allows the execution of arbitrary code. That makes it a major security106   risk and therefore it **must never be used on production machines**.107108Screenshot of the debugger in action:109110.. image:: _static/debugger.png111   :align: center112   :class: screenshot113   :alt: screenshot of debugger in action114115.. admonition:: Working With Other Debuggers116117   Debuggers interfere with each other.  118   That said, you may still wish to use the debugger in a tool of your choice. 119   Flask provides the following options to manage the debug process:120121   * ``debug``        - whether to enable debug mode and catch exceptinos122   * ``use_debugger`` - whether to use the internal Flask debugger123   * ``use_reloader`` - whether to reload and fork the process on exception124125   ``debug`` must be True (i.e., exceptions must caught) in order for the 126   other two options to have any value.127128   If you're using Aptana/Eclipse for debugging you'll need to set both 129   ``use_debugger`` and ``use_reloader`` to False.130131   A possible useful pattern for configuration is to set the following in your 132   config.yaml (change the block as approriate for your application, of course)::133134       FLASK:135           DEBUG: True136           DEBUG_WITH_APTANA: True137138   Then in your application's entry-point (main.py), you could have something like::139140       if __name__ == "__main__":141           # To allow aptana to receive errors, set use_debugger=False142           app = create_app(config="config.yaml")143144           if app.debug: use_debugger = True145           try:146               # Disable Flask's debugger if external debugger is requested147               use_debugger = not(app.config.get('DEBUG_WITH_APTANA'))148           except:149               pass150           app.run(use_debugger=use_debugger, debug=app.debug, use_reloader=use_debugger, host='0.0.0.0')151152153Routing154-------155156Modern web applications have beautiful URLs.  This helps people remember157the URLs, which is especially handy for applications that are used from158mobile devices with slower network connections.  If the user can directly159go to the desired page without having to hit the index page it is more160likely they will like the page and come back next time.161162As you have seen above, the :meth:`~flask.Flask.route` decorator is used163to bind a function to a URL.  Here are some basic examples::164165    @app.route('/')166    def index():167        return 'Index Page'168169    @app.route('/hello')170    def hello():171        return 'Hello World'172173But there is more to it!  You can make certain parts of the URL dynamic174and attach multiple rules to a function.175176Variable Rules177``````````````178179To add variable parts to a URL you can mark these special sections as180``<variable_name>``.  Such a part is then passed as keyword argument to181your function.  Optionally a converter can be specified by specifying a182rule with ``<converter:variable_name>``.  Here are some nice examples::183184    @app.route('/user/<username>')185    def show_user_profile(username):186        # show the user profile for that user187        return 'User %s' % username188189    @app.route('/post/<int:post_id>')190    def show_post(post_id):191        # show the post with the given id, the id is an integer192        return 'Post %d' % post_id193194The following converters exist:195196=========== ===========================================197`int`       accepts integers198`float`     like `int` but for floating point values199`path`      like the default but also accepts slashes200=========== ===========================================201202.. admonition:: Unique URLs / Redirection Behaviour203204   Flask's URL rules are based on Werkzeug's routing module.  The idea205   behind that module is to ensure nice-looking and also unique URLs based206   on behaviour coined by Apache and earlier servers.207208   Take these two rules::209210        @app.route('/projects/')211        def projects():212            return 'The project page'213214        @app.route('/about')215        def about():216            return 'The about page'217218   They look rather similar, the difference is the trailing slash in the219   URL *definition*.  In the first case, the canonical URL for the220   `projects` endpoint has a trailing slash.  It's similar to a folder in221   that sense.  Accessing it without a trailing slash will cause Flask to222   redirect to the canonical URL with the trailing slash.223224   However, in the second case the URL is defined without a slash so it225   behaves similar to a file and accessing the URL with a trailing slash226   will result in a 404 error.227228   Why is this?  This allows relative URLs to continue working if users229   access the page when they forget a trailing slash.  This behaviour is230   also consistent with how Apache and other servers work.  Also, the URLs231   will stay unique which ensures search engines do not index the same page232   twice.233234235.. _url-building:236237URL Building238````````````239240If it can match URLs, can it also generate them?  Of course it can.  To241build a URL to a specific function you can use the :func:`~flask.url_for`242function.  It accepts the name of the function as first argument and a243number of keyword arguments, each corresponding to the variable part of244the URL rule.  Unknown variable parts are appended to the URL as query245parameter.  Here are some examples:246247>>> from flask import Flask, url_for248>>> app = Flask(__name__)249>>> @app.route('/')250... def index(): pass251...252>>> @app.route('/login')253... def login(): pass254...255>>> @app.route('/user/<username>')256... def profile(username): pass257...258>>> with app.test_request_context():259...  print url_for('index')260...  print url_for('login')261...  print url_for('login', next='/')262...  print url_for('profile', username='John Doe')263...264/265/login266/login?next=/267/user/John%20Doe268269(This also uses the :meth:`~flask.Flask.test_request_context` method270explained below.  It basically tells Flask to think we are handling a271request even though we are not, we are in an interactive Python shell.272Have a look at the explanation below: :ref:`context-locals`.)273274Why would you want to build URLs instead of hardcoding them in your275templates?  There are three good reasons for this:2762771. reversing is often more descriptive than hardcoding the URLs.  Also and278   more importantly you can change URLs in one go without having to change279   the URLs all over the place.2802. URL building will handle escaping of special characters and Unicode281   data transparently for you, you don't have to deal with that.2823. If your application is placed outside the URL root (so say in283   ``/myapplication`` instead of ``/``), :func:`~flask.url_for` will284   handle that properly for you.285286287HTTP Methods288````````````289290HTTP (the protocol web applications are speaking) knows different methods291to access URLs.  By default a route only answers to `GET` requests, but292that can be changed by providing the `methods` argument to the293:meth:`~flask.Flask.route` decorator.  Here are some examples::294295    @app.route('/login', methods=['GET', 'POST'])296    def login():297        if request.method == 'POST':298            do_the_login()299        else:300            show_the_login_form()301302If `GET` is present, `HEAD` will be added automatically for you.  You303don't have to deal with that.  It will also make sure that `HEAD` requests304are handled as the `HTTP RFC`_ (the document describing the HTTP305protocol) demands, so you can completely ignore that part of the HTTP306specification.  Likewise, as of Flask 0.6, `OPTIONS` is implemented for you307automatically as well.308309You have no idea what an HTTP method is?  Worry not, here is a quick310introduction to HTTP methods and why they matter:311312The HTTP method (also often called "the verb") tells the server what the313clients wants to *do* with the requested page.  The following methods are314very common:315316`GET`317    The browser tells the server to just *get* the information stored on318    that page and send it.  This is probably the most common method.319320`HEAD`321    The browser tells the server to get the information, but it is only322    interested in the *headers*, not the content of the page.  An323    application is supposed to handle that as if a `GET` request was324    received but to not deliver the actual content.  In Flask you don't325    have to deal with that at all, the underlying Werkzeug library handles326    that for you.327328`POST`329    The browser tells the server that it wants to *post* some new330    information to that URL and that the server must ensure the data is331    stored and only stored once.  This is how HTML forms usually332    transmit data to the server.333334`PUT`335    Similar to `POST` but the server might trigger the store procedure336    multiple times by overwriting the old values more than once.  Now you337    might be asking why this is useful, but there are some good reasons338    to do it this way.  Consider that the connection is lost during339    transmission: in this situation a system between the browser and the340    server might receive the request safely a second time without breaking341    things.  With `POST` that would not be possible because it must only342    be triggered once.343344`DELETE`345    Remove the information at the given location.346347`OPTIONS`348    Provides a quick way for a client to figure out which methods are349    supported by this URL.  Starting with Flask 0.6, this is implemented350    for you automatically.351352Now the interesting part is that in HTML4 and XHTML1, the only methods a353form can submit to the server are `GET` and `POST`.  But with JavaScript354and future HTML standards you can use the other methods as well.  Furthermore355HTTP has become quite popular lately and browsers are no longer the only356clients that are using HTTP. For instance, many revision control system357use it.358359.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt360361Static Files362------------363364Dynamic web applications also need static files.  That's usually where365the CSS and JavaScript files are coming from.  Ideally your web server is366configured to serve them for you, but during development Flask can do that367as well.  Just create a folder called `static` in your package or next to368your module and it will be available at `/static` on the application.369370To generate URLs that part of the URL, use the special ``'static'`` URL371name::372373    url_for('static', filename='style.css')374375The file has to be stored on the filesystem as ``static/style.css``.376377Rendering Templates378-------------------379380Generating HTML from within Python is not fun, and actually pretty381cumbersome because you have to do the HTML escaping on your own to keep382the application secure.  Because of that Flask configures the `Jinja2383<http://jinja.pocoo.org/2/>`_ template engine for you automatically.384385To render a template you can use the :func:`~flask.render_template`386method.  All you have to do is provide the name of the template and the387variables you want to pass to the template engine as keyword arguments.388Here's a simple example of how to render a template::389390    from flask import render_template391392    @app.route('/hello/')393    @app.route('/hello/<name>')394    def hello(name=None):395        return render_template('hello.html', name=name)396397Flask will look for templates in the `templates` folder.  So if your398application is a module, this folder is next to that module, if it's a399package it's actually inside your package:400401**Case 1**: a module::402403    /application.py404    /templates405        /hello.html406407**Case 2**: a package::408409    /application410        /__init__.py411        /templates412            /hello.html413414For templates you can use the full power of Jinja2 templates.  Head over415to the the official `Jinja2 Template Documentation416<http://jinja.pocoo.org/2/documentation/templates>`_ for more information.417418Here is an example template:419420.. sourcecode:: html+jinja421422    <!doctype html>423    <title>Hello from Flask</title>424    {% if name %}425      <h1>Hello {{ name }}!</h1>426    {% else %}427      <h1>Hello World!</h1>428    {% endif %}429430Inside templates you also have access to the :class:`~flask.request`,431:class:`~flask.session` and :class:`~flask.g` [#]_ objects432as well as the :func:`~flask.get_flashed_messages` function.433434Templates are especially useful if inheritance is used.  If you want to435know how that works, head over to the :ref:`template-inheritance` pattern436documentation.  Basically template inheritance makes it possible to keep437certain elements on each page (like header, navigation and footer).438439Automatic escaping is enabled, so if `name` contains HTML it will be escaped440automatically.  If you can trust a variable and you know that it will be441safe HTML (for example because it came from a module that converts wiki442markup to HTML) you can mark it as safe by using the443:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the444template.  Head over to the Jinja 2 documentation for more examples.445446Here is a basic introduction to how the :class:`~jinja2.Markup` class works:447448>>> from flask import Markup449>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'450Markup(u'<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')451>>> Markup.escape('<blink>hacker</blink>')452Markup(u'&lt;blink&gt;hacker&lt;/blink&gt;')453>>> Markup('<em>Marked up</em> &raquo; HTML').striptags()454u'Marked up \xbb HTML'455456.. versionchanged:: 0.5457458   Autoescaping is no longer enabled for all templates.  The following459   extensions for templates trigger autoescaping: ``.html``, ``.htm``,460   ``.xml``, ``.xhtml``.  Templates loaded from a string will have461   autoescaping disabled.462463.. [#] Unsure what that :class:`~flask.g` object is? It's something in which464   you can store information for your own needs, check the documentation of465   that object (:class:`~flask.g`) and the :ref:`sqlite3` for more466   information.467468469Accessing Request Data470----------------------471472For web applications it's crucial to react to the data a client sent to473the server.  In Flask this information is provided by the global474:class:`~flask.request` object.  If you have some experience with Python475you might be wondering how that object can be global and how Flask476manages to still be threadsafe.  The answer is context locals:477478479.. _context-locals:480481Context Locals482``````````````483484.. admonition:: Insider Information485486   If you want to understand how that works and how you can implement487   tests with context locals, read this section, otherwise just skip it.488489Certain objects in Flask are global objects, but not of the usual kind.490These objects are actually proxies to objects that are local to a specific491context.  What a mouthful.  But that is actually quite easy to understand.492493Imagine the context being the handling thread.  A request comes in and the494web server decides to spawn a new thread (or something else, the495underlying object is capable of dealing with concurrency systems other496than threads).  When Flask starts its internal request handling it497figures out that the current thread is the active context and binds the498current application and the WSGI environments to that context (thread).499It does that in an intelligent way so that one application can invoke another500application without breaking.501502So what does this mean to you?  Basically you can completely ignore that503this is the case unless you are doing something like unit testing.  You504will notice that code which depends on a request object will suddenly break505because there is no request object.  The solution is creating a request506object yourself and binding it to the context.  The easiest solution for507unit testing is to use the :meth:`~flask.Flask.test_request_context`508context manager.  In combination with the `with` statement it will bind a509test request so that you can interact with it.  Here is an example::510511    from flask import request512513    with app.test_request_context('/hello', method='POST'):514        # now you can do something with the request until the515        # end of the with block, such as basic assertions:516        assert request.path == '/hello'517        assert request.method == 'POST'518519The other possibility is passing a whole WSGI environment to the520:meth:`~flask.Flask.request_context` method::521522    from flask import request523524    with app.request_context(environ):525        assert request.method == 'POST'526527The Request Object528``````````````````529530The request object is documented in the API section and we will not cover531it here in detail (see :class:`~flask.request`). Here is a broad overview of532some of the most common operations.  First of all you have to import it from533the `flask` module::534535    from flask import request536537The current request method is available by using the538:attr:`~flask.request.method` attribute.  To access form data (data539transmitted in a `POST` or `PUT` request) you can use the540:attr:`~flask.request.form` attribute.  Here is a full example of the two541attributes mentioned above::542543    @app.route('/login', methods=['POST', 'GET'])544    def login():545        error = None546        if request.method == 'POST':547            if valid_login(request.form['username'],548                           request.form['password']):549                return log_the_user_in(request.form['username'])550            else:551                error = 'Invalid username/password'552        # this is executed if the request method was GET or the553        # credentials were invalid554555What happens if the key does not exist in the `form` attribute?  In that556case a special :exc:`KeyError` is raised.  You can catch it like a557standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request558error page is shown instead.  So for many situations you don't have to559deal with that problem.560561To access parameters submitted in the URL (``?key=value``) you can use the562:attr:`~flask.request.args` attribute::563564    searchword = request.args.get('q', '')565566We recommend accessing URL parameters with `get` or by catching the567`KeyError` because users might change the URL and presenting them a 400568bad request page in that case is not user friendly.569570For a full list of methods and attributes of the request object, head over571to the :class:`~flask.request` documentation.572573574File Uploads575````````````576577You can handle uploaded files with Flask easily.  Just make sure not to578forget to set the ``enctype="multipart/form-data"`` attribute on your HTML579form, otherwise the browser will not transmit your files at all.580581Uploaded files are stored in memory or at a temporary location on the582filesystem.  You can access those files by looking at the583:attr:`~flask.request.files` attribute on the request object.  Each584uploaded file is stored in that dictionary.  It behaves just like a585standard Python :class:`file` object, but it also has a586:meth:`~werkzeug.datastructures.FileStorage.save` method that allows you to store that587file on the filesystem of the server.  Here is a simple example showing how588that works::589590    from flask import request591592    @app.route('/upload', methods=['GET', 'POST'])593    def upload_file():594        if request.method == 'POST':595            f = request.files['the_file']596            f.save('/var/www/uploads/uploaded_file.txt')597        ...598599If you want to know how the file was named on the client before it was600uploaded to your application, you can access the601:attr:`~werkzeug.datastructures.FileStorage.filename` attribute.  However please keep in602mind that this value can be forged so never ever trust that value.  If you603want to use the filename of the client to store the file on the server,604pass it through the :func:`~werkzeug.utils.secure_filename` function that605Werkzeug provides for you::606607    from flask import request608    from werkzeug import secure_filename609610    @app.route('/upload', methods=['GET', 'POST'])611    def upload_file():612        if request.method == 'POST':613            f = request.files['the_file']614            f.save('/var/www/uploads/' + secure_filename(f.filename))615        ...616617For some better examples, checkout the :ref:`uploading-files` pattern.618619Cookies620```````621622To access cookies you can use the :attr:`~flask.Request.cookies`623attribute.  To set cookies you can use the624:attr:`~flask.Response.set_cookie` method of response objects.  The625:attr:`~flask.Request.cookies` attribute of request objects is a626dictionary with all the cookies the client transmits.  If you want to use627sessions, do not use the cookies directly but instead use the628:ref:`sessions` in Flask that add some security on top of cookies for you.629630Reading cookies::631632    from flask import request633634    @app.route('/')635    def index():636        username = request.cookies.get('username')637        # use cookies.get(key) instead of cookies[key] to not get a638        # KeyError if the cookie is missing.639640Storing cookies::641642    from flask import make_response643644    @app.route('/')645    def index():646        resp = make_response(render_template(...))647        resp.set_cookie('username', 'the username')648        return resp649650Note that cookies are set on response objects.  Since you normally651just return strings from the view functions Flask will convert them into652response objects for you.  If you explicitly want to do that you can use653the :meth:`~flask.make_response` function and then modify it.654655Sometimes you might want to set a cookie at a point where the response656object does not exist yet.  This is possible by utilizing the657:ref:`deferred-callbacks` pattern.658659For this also see :ref:`about-responses`.660661Redirects and Errors662--------------------663664To redirect a user to somewhere else you can use the665:func:`~flask.redirect` function. To abort a request early with an error666code use the :func:`~flask.abort` function.  Here an example how this works::667668    from flask import abort, redirect, url_for669670    @app.route('/')671    def index():672        return redirect(url_for('login'))673674    @app.route('/login')675    def login():676        abort(401)677        this_is_never_executed()678679This is a rather pointless example because a user will be redirected from680the index to a page they cannot access (401 means access denied) but it681shows how that works.682683By default a black and white error page is shown for each error code.  If684you want to customize the error page, you can use the685:meth:`~flask.Flask.errorhandler` decorator::686687    from flask import render_template688689    @app.errorhandler(404)690    def page_not_found(error):691        return render_template('page_not_found.html'), 404692693Note the ``404`` after the :func:`~flask.render_template` call.  This694tells Flask that the status code of that page should be 404 which means695not found.  By default 200 is assumed which translates to: all went well.696697.. _about-responses:698699About Responses700---------------701702The return value from a view function is automatically converted into a703response object for you.  If the return value is a string it's converted704into a response object with the string as response body, an ``200 OK``705error code and a ``text/html`` mimetype.  The logic that Flask applies to706converting return values into response objects is as follows:7077081.  If a response object of the correct type is returned it's directly709    returned from the view.7102.  If it's a string, a response object is created with that data and the711    default parameters.7123.  If a tuple is returned the response object is created by passing the713    tuple as arguments to the response object's constructor.7144.  If none of that works, Flask will assume the return value is a715    valid WSGI application and convert that into a response object.716717If you want to get hold of the resulting response object inside the view718you can use the :func:`~flask.make_response` function.719720Imagine you have a view like this:721722.. sourcecode:: python723724    @app.errorhandler(404)725    def not_found(error):726        return render_template('error.html'), 404727728You just need to wrap the return expression with729:func:`~flask.make_response` and get the result object to modify it, then730return it:731732.. sourcecode:: python733734    @app.errorhandler(404)735    def not_found(error):736        resp = make_response(render_template('error.html'), 404)737        resp.headers['X-Something'] = 'A value'738        return resp739740.. _sessions:741742Sessions743--------744745In addition to the request object there is also a second object called746:class:`~flask.session` which allows you to store information specific to a747user from one request to the next.  This is implemented on top of cookies748for you and signs the cookies cryptographically.  What this means is that749the user could look at the contents of your cookie but not modify it,750unless they know the secret key used for signing.751752In order to use sessions you have to set a secret key.  Here is how753sessions work::754755    from flask import Flask, session, redirect, url_for, escape, request756757    app = Flask(__name__)758759    @app.route('/')760    def index():761        if 'username' in session:762            return 'Logged in as %s' % escape(session['username'])763        return 'You are not logged in'764765    @app.route('/login', methods=['GET', 'POST'])766    def login():767        if request.method == 'POST':768            session['username'] = request.form['username']769            return redirect(url_for('index'))770        return '''771            <form action="" method="post">772                <p><input type=text name=username>773                <p><input type=submit value=Login>774            </form>775        '''776777    @app.route('/logout')778    def logout():779        # remove the username from the session if its there780        session.pop('username', None)781        return redirect(url_for('index'))782783    # set the secret key.  keep this really secret:784    app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'785786The :func:`~flask.escape` mentioned here does escaping for you if you are787not using the template engine (as in this example).788789.. admonition:: How to generate good secret keys790791   The problem with random is that it's hard to judge what is truly random.  And792   a secret key should be as random as possible.  Your operating system793   has ways to generate pretty random stuff based on a cryptographic794   random generator which can be used to get such a key:795796   >>> import os797   >>> os.urandom(24)798   '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'799800   Just take that thing and copy/paste it into your code and you're done.801802Message Flashing803----------------804805Good applications and user interfaces are all about feedback.  If the user806does not get enough feedback they will probably end up hating the807application.  Flask provides a really simple way to give feedback to a808user with the flashing system.  The flashing system basically makes it809possible to record a message at the end of a request and access it on the next810(and only the next) request.  This is usually combined with a layout811template to expose the message.812813To flash a message use the :func:`~flask.flash` method, to get hold of the814messages you can use :func:`~flask.get_flashed_messages` which is also815available in the templates.  Check out the :ref:`message-flashing-pattern`816for a full example.817818Logging819-------820821.. versionadded:: 0.3822823Sometimes you might be in a situation where you deal with data that824should be correct, but actually is not.  For example you may have some client-side825code that sends an HTTP request to the server but it's obviously826malformed.  This might be caused by a user tampering with the data, or the827client code failing.  Most of the time it's okay to reply with ``400 Bad828Request`` in that situation, but sometimes that won't do and the code has829to continue working.830831You may still want to log that something fishy happened.  This is where832loggers come in handy.  As of Flask 0.3 a logger is preconfigured for you833to use.834835Here are some example log calls::836837    app.logger.debug('A value for debugging')838    app.logger.warning('A warning occurred (%d apples)', 42)839    app.logger.error('An error occurred')840841The attached :attr:`~flask.Flask.logger` is a standard logging842:class:`~logging.Logger`, so head over to the official `logging843documentation <http://docs.python.org/library/logging.html>`_ for more844information.845846Hooking in WSGI Middlewares847---------------------------848849If you want to add a WSGI middleware to your application you can wrap the850internal WSGI application.  For example if you want to use one of the851middlewares from the Werkzeug package to work around bugs in lighttpd, you852can do it like this::853854    from werkzeug.contrib.fixers import LighttpdCGIRootFix855    app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)