Skip to content
Myr

quickstart.rst

This file

Path

docs/quickstart.rst

855 lines · 31.3 KiB

Last changed by

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption36e86be

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!'2223    if __name__ == '__main__':24        app.run()2526Just save it as `hello.py` (or something similar) and run it with your Python27interpreter.  Make sure to not call your application `flask.py` because this28would conflict with Flask itself.2930::3132    $ python hello.py33     * Running on http://127.0.0.1:5000/3435Now head over to `http://127.0.0.1:5000/ <http://127.0.0.1:5000/>`_, and you36should see 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.  422. Next we create an instance of this class. The first argument is the name of43   the application's module or package.  If you are using a single module (as44   in this example), you should use `__name__` because depending on if it's45   started as application or imported as module the name will be different46   (``'__main__'`` versus the actual import name). This is needed so that47   Flask knows where to look for templates, static files, and so on. For more48   information have a look at the :class:`~flask.Flask` documentation.493. We then use the :meth:`~flask.Flask.route` decorator to tell Flask what URL50   should trigger our function.514. The function is given a name which is also used to generate URLs for that52   particular function, and returns the message we want to display in the53   user's browser.545. Finally we use the :meth:`~flask.Flask.run` function to run the local server55   with our application.  The ``if __name__ == '__main__':`` makes sure the56   server only runs if the script is executed directly from the Python57   interpreter and not used as an imported module.5859To stop the server, hit control-C.6061.. _public-server:6263.. admonition:: Externally Visible Server6465   If you run the server you will notice that the server is only accessible66   from your own computer, not from any other in the network.  This is the67   default because in debugging mode a user of the application can execute68   arbitrary Python code on your computer.6970   If you have `debug` disabled or trust the users on your network, you can71   make the server publicly available simply by changing the call of the72   :meth:`~flask.Flask.run` method to look like this::7374       app.run(host='0.0.0.0')7576   This tells your operating system to listen on all public IPs.777879.. _debug-mode:8081Debug Mode82----------8384The :meth:`~flask.Flask.run` method is nice to start a local85development server, but you would have to restart it manually after each86change to your code.  That is not very nice and Flask can do better.  If87you enable debug support the server will reload itself on code changes,88and it will also provide you with a helpful debugger if things go wrong.8990There are two ways to enable debugging.  Either set that flag on the91application object::9293    app.debug = True94    app.run()9596Or pass it as a parameter to run::9798    app.run(debug=True)99100Both methods have the exact same effect.101102.. admonition:: Attention103104   Even though the interactive debugger does not work in forking environments105   (which makes it nearly impossible to use on production servers), it still106   allows the execution of arbitrary code. This makes it a major security risk107   and therefore it **must never be used on production machines**.108109Screenshot of the debugger in action:110111.. image:: _static/debugger.png112   :align: center113   :class: screenshot114   :alt: screenshot of debugger in action115116Have another debugger in mind? See :ref:`working-with-debuggers`.117118119Routing120-------121122Modern web applications have beautiful URLs.  This helps people remember123the URLs, which is especially handy for applications that are used from124mobile devices with slower network connections.  If the user can directly125go to the desired page without having to hit the index page it is more126likely they will like the page and come back next time.127128As you have seen above, the :meth:`~flask.Flask.route` decorator is used to129bind a function to a URL.  Here are some basic examples::130131    @app.route('/')132    def index():133        return 'Index Page'134135    @app.route('/hello')136    def hello():137        return 'Hello World'138139But there is more to it!  You can make certain parts of the URL dynamic and140attach multiple rules to a function.141142Variable Rules143``````````````144145To add variable parts to a URL you can mark these special sections as146``<variable_name>``.  Such a part is then passed as a keyword argument to your147function.  Optionally a converter can be used by specifying a rule with148``<converter:variable_name>``.  Here are some nice examples::149150    @app.route('/user/<username>')151    def show_user_profile(username):152        # show the user profile for that user153        return 'User %s' % username154155    @app.route('/post/<int:post_id>')156    def show_post(post_id):157        # show the post with the given id, the id is an integer158        return 'Post %d' % post_id159160The following converters exist:161162=========== ===========================================163`int`       accepts integers164`float`     like `int` but for floating point values165`path`      like the default but also accepts slashes166=========== ===========================================167168.. admonition:: Unique URLs / Redirection Behavior169170   Flask's URL rules are based on Werkzeug's routing module.  The idea171   behind that module is to ensure beautiful and unique URLs based on172   precedents laid down by Apache and earlier HTTP servers.173174   Take these two rules::175176        @app.route('/projects/')177        def projects():178            return 'The project page'179180        @app.route('/about')181        def about():182            return 'The about page'183184   Though they look rather similar, they differ in their use of the trailing185   slash in the URL *definition*.  In the first case, the canonical URL for the186   `projects` endpoint has a trailing slash.  In that sense, it is similar to187   a folder on a file system.  Accessing it without a trailing slash will cause188   Flask to redirect to the canonical URL with the trailing slash.189190   In the second case, however, the URL is defined without a trailing slash,191   rather like the pathname of a file on UNIX-like systems. Accessing the URL192   with a trailing slash will produce a 404 "Not Found" error.193194   This behavior allows relative URLs to continue working even if the trailing195   slash is omitted, consistent with how Apache and other servers work.  Also,196   the URLs will stay unique, which helps search engines avoid indexing the197   same page twice.198199200.. _url-building:201202URL Building203````````````204205If it can match URLs, can Flask also generate them?  Of course it can.  To206build a URL to a specific function you can use the :func:`~flask.url_for`207function.  It accepts the name of the function as first argument and a number208of keyword arguments, each corresponding to the variable part of the URL rule.209Unknown variable parts are appended to the URL as query parameters.  Here are210some examples:211212>>> from flask import Flask, url_for213>>> app = Flask(__name__)214>>> @app.route('/')215... def index(): pass216...217>>> @app.route('/login')218... def login(): pass219...220>>> @app.route('/user/<username>')221... def profile(username): pass222...223>>> with app.test_request_context():224...  print url_for('index')225...  print url_for('login')226...  print url_for('login', next='/')227...  print url_for('profile', username='John Doe')228...229/230/login231/login?next=/232/user/John%20Doe233234(This also uses the :meth:`~flask.Flask.test_request_context` method, explained235below.  It tells Flask to behave as though it is handling a request, even236though we are interacting with it through a Python shell.  Have a look at the237explanation below. :ref:`context-locals`).238239Why would you want to build URLs using the URL reversing function :func:`~flask.url_for` 240instead of hard-coding them into your templates?  There are three good reasons 241for this:2422431. Reversing is often more descriptive than hard-coding the URLs.  More244   importantly, it allows you to change URLs in one go, without having to245   remember to change URLs all over the place.2462. URL building will handle escaping of special characters and Unicode247   data transparently for you, so you don't have to deal with them.2483. If your application is placed outside the URL root (say, in249   ``/myapplication`` instead of ``/``), :func:`~flask.url_for` will handle250   that properly for you.251252253HTTP Methods254````````````255256HTTP (the protocol web applications are speaking) knows different methods for257accessing URLs.  By default, a route only answers to `GET` requests, but that258can be changed by providing the `methods` argument to the259:meth:`~flask.Flask.route` decorator.  Here are some examples::260261    from flask import request262263    @app.route('/login', methods=['GET', 'POST'])264    def login():265        if request.method == 'POST':266            do_the_login()267        else:268            show_the_login_form()269270If `GET` is present, `HEAD` will be added automatically for you.  You271don't have to deal with that.  It will also make sure that `HEAD` requests272are handled as the `HTTP RFC`_ (the document describing the HTTP273protocol) demands, so you can completely ignore that part of the HTTP274specification.  Likewise, as of Flask 0.6, `OPTIONS` is implemented for you275automatically as well.276277You have no idea what an HTTP method is?  Worry not, here is a quick278introduction to HTTP methods and why they matter:279280The HTTP method (also often called "the verb") tells the server what the281clients wants to *do* with the requested page.  The following methods are282very common:283284`GET`285    The browser tells the server to just *get* the information stored on286    that page and send it.  This is probably the most common method.287288`HEAD`289    The browser tells the server to get the information, but it is only290    interested in the *headers*, not the content of the page.  An291    application is supposed to handle that as if a `GET` request was292    received but to not deliver the actual content.  In Flask you don't293    have to deal with that at all, the underlying Werkzeug library handles294    that for you.295296`POST`297    The browser tells the server that it wants to *post* some new298    information to that URL and that the server must ensure the data is299    stored and only stored once.  This is how HTML forms usually300    transmit data to the server.301302`PUT`303    Similar to `POST` but the server might trigger the store procedure304    multiple times by overwriting the old values more than once.  Now you305    might be asking why this is useful, but there are some good reasons306    to do it this way.  Consider that the connection is lost during307    transmission: in this situation a system between the browser and the308    server might receive the request safely a second time without breaking309    things.  With `POST` that would not be possible because it must only310    be triggered once.311312`DELETE`313    Remove the information at the given location.314315`OPTIONS`316    Provides a quick way for a client to figure out which methods are317    supported by this URL.  Starting with Flask 0.6, this is implemented318    for you automatically.319320Now the interesting part is that in HTML4 and XHTML1, the only methods a321form can submit to the server are `GET` and `POST`.  But with JavaScript322and future HTML standards you can use the other methods as well.  Furthermore323HTTP has become quite popular lately and browsers are no longer the only324clients that are using HTTP. For instance, many revision control systems325use it.326327.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt328329Static Files330------------331332Dynamic web applications also need static files.  That's usually where333the CSS and JavaScript files are coming from.  Ideally your web server is334configured to serve them for you, but during development Flask can do that335as well.  Just create a folder called `static` in your package or next to336your module and it will be available at `/static` on the application.337338To generate URLs for static files, use the special ``'static'`` endpoint name::339340    url_for('static', filename='style.css')341342The file has to be stored on the filesystem as ``static/style.css``.343344Rendering Templates345-------------------346347Generating HTML from within Python is not fun, and actually pretty348cumbersome because you have to do the HTML escaping on your own to keep349the application secure.  Because of that Flask configures the `Jinja2350<http://jinja.pocoo.org/2/>`_ template engine for you automatically.351352To render a template you can use the :func:`~flask.render_template`353method.  All you have to do is provide the name of the template and the354variables you want to pass to the template engine as keyword arguments.355Here's a simple example of how to render a template::356357    from flask import render_template358359    @app.route('/hello/')360    @app.route('/hello/<name>')361    def hello(name=None):362        return render_template('hello.html', name=name)363364Flask will look for templates in the `templates` folder.  So if your365application is a module, this folder is next to that module, if it's a366package it's actually inside your package:367368**Case 1**: a module::369370    /application.py371    /templates372        /hello.html373374**Case 2**: a package::375376    /application377        /__init__.py378        /templates379            /hello.html380381For templates you can use the full power of Jinja2 templates.  Head over382to the official `Jinja2 Template Documentation383<http://jinja.pocoo.org/2/documentation/templates>`_ for more information.384385Here is an example template:386387.. sourcecode:: html+jinja388389    <!doctype html>390    <title>Hello from Flask</title>391    {% if name %}392      <h1>Hello {{ name }}!</h1>393    {% else %}394      <h1>Hello World!</h1>395    {% endif %}396397Inside templates you also have access to the :class:`~flask.request`,398:class:`~flask.session` and :class:`~flask.g` [#]_ objects399as well as the :func:`~flask.get_flashed_messages` function.400401Templates are especially useful if inheritance is used.  If you want to402know how that works, head over to the :ref:`template-inheritance` pattern403documentation.  Basically template inheritance makes it possible to keep404certain elements on each page (like header, navigation and footer).405406Automatic escaping is enabled, so if `name` contains HTML it will be escaped407automatically.  If you can trust a variable and you know that it will be408safe HTML (for example because it came from a module that converts wiki409markup to HTML) you can mark it as safe by using the410:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the411template.  Head over to the Jinja 2 documentation for more examples.412413Here is a basic introduction to how the :class:`~jinja2.Markup` class works:414415>>> from flask import Markup416>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'417Markup(u'<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')418>>> Markup.escape('<blink>hacker</blink>')419Markup(u'&lt;blink&gt;hacker&lt;/blink&gt;')420>>> Markup('<em>Marked up</em> &raquo; HTML').striptags()421u'Marked up \xbb HTML'422423.. versionchanged:: 0.5424425   Autoescaping is no longer enabled for all templates.  The following426   extensions for templates trigger autoescaping: ``.html``, ``.htm``,427   ``.xml``, ``.xhtml``.  Templates loaded from a string will have428   autoescaping disabled.429430.. [#] Unsure what that :class:`~flask.g` object is? It's something in which431   you can store information for your own needs, check the documentation of432   that object (:class:`~flask.g`) and the :ref:`sqlite3` for more433   information.434435436Accessing Request Data437----------------------438439For web applications it's crucial to react to the data a client sent to440the server.  In Flask this information is provided by the global441:class:`~flask.request` object.  If you have some experience with Python442you might be wondering how that object can be global and how Flask443manages to still be threadsafe.  The answer is context locals:444445446.. _context-locals:447448Context Locals449``````````````450451.. admonition:: Insider Information452453   If you want to understand how that works and how you can implement454   tests with context locals, read this section, otherwise just skip it.455456Certain objects in Flask are global objects, but not of the usual kind.457These objects are actually proxies to objects that are local to a specific458context.  What a mouthful.  But that is actually quite easy to understand.459460Imagine the context being the handling thread.  A request comes in and the461web server decides to spawn a new thread (or something else, the462underlying object is capable of dealing with concurrency systems other463than threads).  When Flask starts its internal request handling it464figures out that the current thread is the active context and binds the465current application and the WSGI environments to that context (thread).466It does that in an intelligent way so that one application can invoke another467application without breaking.468469So what does this mean to you?  Basically you can completely ignore that470this is the case unless you are doing something like unit testing.  You471will notice that code which depends on a request object will suddenly break472because there is no request object.  The solution is creating a request473object yourself and binding it to the context.  The easiest solution for474unit testing is to use the :meth:`~flask.Flask.test_request_context`475context manager.  In combination with the `with` statement it will bind a476test request so that you can interact with it.  Here is an example::477478    from flask import request479480    with app.test_request_context('/hello', method='POST'):481        # now you can do something with the request until the482        # end of the with block, such as basic assertions:483        assert request.path == '/hello'484        assert request.method == 'POST'485486The other possibility is passing a whole WSGI environment to the487:meth:`~flask.Flask.request_context` method::488489    from flask import request490491    with app.request_context(environ):492        assert request.method == 'POST'493494The Request Object495``````````````````496497The request object is documented in the API section and we will not cover498it here in detail (see :class:`~flask.request`). Here is a broad overview of499some of the most common operations.  First of all you have to import it from500the `flask` module::501502    from flask import request503504The current request method is available by using the505:attr:`~flask.request.method` attribute.  To access form data (data506transmitted in a `POST` or `PUT` request) you can use the507:attr:`~flask.request.form` attribute.  Here is a full example of the two508attributes mentioned above::509510    @app.route('/login', methods=['POST', 'GET'])511    def login():512        error = None513        if request.method == 'POST':514            if valid_login(request.form['username'],515                           request.form['password']):516                return log_the_user_in(request.form['username'])517            else:518                error = 'Invalid username/password'519        # the code below is executed if the request method520        # was GET or the credentials were invalid521        return render_template('login.html', error=error)522523What happens if the key does not exist in the `form` attribute?  In that524case a special :exc:`KeyError` is raised.  You can catch it like a525standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request526error page is shown instead.  So for many situations you don't have to527deal with that problem.528529To access parameters submitted in the URL (``?key=value``) you can use the530:attr:`~flask.request.args` attribute::531532    searchword = request.args.get('key', '')533534We recommend accessing URL parameters with `get` or by catching the535`KeyError` because users might change the URL and presenting them a 400536bad request page in that case is not user friendly.537538For a full list of methods and attributes of the request object, head over539to the :class:`~flask.request` documentation.540541542File Uploads543````````````544545You can handle uploaded files with Flask easily.  Just make sure not to546forget to set the ``enctype="multipart/form-data"`` attribute on your HTML547form, otherwise the browser will not transmit your files at all.548549Uploaded files are stored in memory or at a temporary location on the550filesystem.  You can access those files by looking at the551:attr:`~flask.request.files` attribute on the request object.  Each552uploaded file is stored in that dictionary.  It behaves just like a553standard Python :class:`file` object, but it also has a554:meth:`~werkzeug.datastructures.FileStorage.save` method that allows you to store that555file on the filesystem of the server.  Here is a simple example showing how556that works::557558    from flask import request559560    @app.route('/upload', methods=['GET', 'POST'])561    def upload_file():562        if request.method == 'POST':563            f = request.files['the_file']564            f.save('/var/www/uploads/uploaded_file.txt')565        ...566567If you want to know how the file was named on the client before it was568uploaded to your application, you can access the569:attr:`~werkzeug.datastructures.FileStorage.filename` attribute.  However please keep in570mind that this value can be forged so never ever trust that value.  If you571want to use the filename of the client to store the file on the server,572pass it through the :func:`~werkzeug.utils.secure_filename` function that573Werkzeug provides for you::574575    from flask import request576    from werkzeug import secure_filename577578    @app.route('/upload', methods=['GET', 'POST'])579    def upload_file():580        if request.method == 'POST':581            f = request.files['the_file']582            f.save('/var/www/uploads/' + secure_filename(f.filename))583        ...584585For some better examples, checkout the :ref:`uploading-files` pattern.586587Cookies588```````589590To access cookies you can use the :attr:`~flask.Request.cookies`591attribute.  To set cookies you can use the592:attr:`~flask.Response.set_cookie` method of response objects.  The593:attr:`~flask.Request.cookies` attribute of request objects is a594dictionary with all the cookies the client transmits.  If you want to use595sessions, do not use the cookies directly but instead use the596:ref:`sessions` in Flask that add some security on top of cookies for you.597598Reading cookies::599600    from flask import request601602    @app.route('/')603    def index():604        username = request.cookies.get('username')605        # use cookies.get(key) instead of cookies[key] to not get a606        # KeyError if the cookie is missing.607608Storing cookies::609610    from flask import make_response611612    @app.route('/')613    def index():614        resp = make_response(render_template(...))615        resp.set_cookie('username', 'the username')616        return resp617618Note that cookies are set on response objects.  Since you normally619just return strings from the view functions Flask will convert them into620response objects for you.  If you explicitly want to do that you can use621the :meth:`~flask.make_response` function and then modify it.622623Sometimes you might want to set a cookie at a point where the response624object does not exist yet.  This is possible by utilizing the625:ref:`deferred-callbacks` pattern.626627For this also see :ref:`about-responses`.628629Redirects and Errors630--------------------631632To redirect a user to another endpoint, use the :func:`~flask.redirect`633function; to abort a request early with an error code, use the634:func:`~flask.abort` function::635636    from flask import abort, redirect, url_for637638    @app.route('/')639    def index():640        return redirect(url_for('login'))641642    @app.route('/login')643    def login():644        abort(401)645        this_is_never_executed()646647This is a rather pointless example because a user will be redirected from648the index to a page they cannot access (401 means access denied) but it649shows how that works.650651By default a black and white error page is shown for each error code.  If652you want to customize the error page, you can use the653:meth:`~flask.Flask.errorhandler` decorator::654655    from flask import render_template656657    @app.errorhandler(404)658    def page_not_found(error):659        return render_template('page_not_found.html'), 404660661Note the ``404`` after the :func:`~flask.render_template` call.  This662tells Flask that the status code of that page should be 404 which means663not found.  By default 200 is assumed which translates to: all went well.664665.. _about-responses:666667About Responses668---------------669670The return value from a view function is automatically converted into a671response object for you.  If the return value is a string it's converted672into a response object with the string as response body, a ``200 OK``673status code and a ``text/html`` mimetype.  The logic that Flask applies to674converting return values into response objects is as follows:6756761.  If a response object of the correct type is returned it's directly677    returned from the view.6782.  If it's a string, a response object is created with that data and the679    default parameters.6803.  If a tuple is returned the items in the tuple can provide extra681    information.  Such tuples have to be in the form ``(response, status,682    headers)`` or ``(response, headers)`` where at least one item has683    to be in the tuple.  The `status` value will override the status code684    and `headers` can be a list or dictionary of additional header values.6854.  If none of that works, Flask will assume the return value is a686    valid WSGI application and convert that into a response object.687688If you want to get hold of the resulting response object inside the view689you can use the :func:`~flask.make_response` function.690691Imagine you have a view like this:692693.. sourcecode:: python694695    @app.errorhandler(404)696    def not_found(error):697        return render_template('error.html'), 404698699You just need to wrap the return expression with700:func:`~flask.make_response` and get the response object to modify it, then701return it:702703.. sourcecode:: python704705    @app.errorhandler(404)706    def not_found(error):707        resp = make_response(render_template('error.html'), 404)708        resp.headers['X-Something'] = 'A value'709        return resp710711.. _sessions:712713Sessions714--------715716In addition to the request object there is also a second object called717:class:`~flask.session` which allows you to store information specific to a718user from one request to the next.  This is implemented on top of cookies719for you and signs the cookies cryptographically.  What this means is that720the user could look at the contents of your cookie but not modify it,721unless they know the secret key used for signing.722723In order to use sessions you have to set a secret key.  Here is how724sessions work::725726    from flask import Flask, session, redirect, url_for, escape, request727728    app = Flask(__name__)729730    @app.route('/')731    def index():732        if 'username' in session:733            return 'Logged in as %s' % escape(session['username'])734        return 'You are not logged in'735736    @app.route('/login', methods=['GET', 'POST'])737    def login():738        if request.method == 'POST':739            session['username'] = request.form['username']740            return redirect(url_for('index'))741        return '''742            <form action="" method="post">743                <p><input type=text name=username>744                <p><input type=submit value=Login>745            </form>746        '''747748    @app.route('/logout')749    def logout():750        # remove the username from the session if it's there751        session.pop('username', None)752        return redirect(url_for('index'))753754    # set the secret key.  keep this really secret:755    app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'756757The :func:`~flask.escape` mentioned here does escaping for you if you are758not using the template engine (as in this example).759760.. admonition:: How to generate good secret keys761762   The problem with random is that it's hard to judge what is truly random.  And763   a secret key should be as random as possible.  Your operating system764   has ways to generate pretty random stuff based on a cryptographic765   random generator which can be used to get such a key:766767   >>> import os768   >>> os.urandom(24)769   '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'770771   Just take that thing and copy/paste it into your code and you're done.772773A note on cookie-based sessions: Flask will take the values you put into the774session object and serialize them into a cookie.  If you are finding some775values do not persist across requests, cookies are indeed enabled, and you are776not getting a clear error message, check the size of the cookie in your page777responses compared to the size supported by web browsers.778779780Message Flashing781----------------782783Good applications and user interfaces are all about feedback.  If the user784does not get enough feedback they will probably end up hating the785application.  Flask provides a really simple way to give feedback to a786user with the flashing system.  The flashing system basically makes it787possible to record a message at the end of a request and access it on the next788(and only the next) request.  This is usually combined with a layout789template to expose the message.790791To flash a message use the :func:`~flask.flash` method, to get hold of the792messages you can use :func:`~flask.get_flashed_messages` which is also793available in the templates.  Check out the :ref:`message-flashing-pattern`794for a full example.795796Logging797-------798799.. versionadded:: 0.3800801Sometimes you might be in a situation where you deal with data that802should be correct, but actually is not.  For example you may have some client-side803code that sends an HTTP request to the server but it's obviously804malformed.  This might be caused by a user tampering with the data, or the805client code failing.  Most of the time it's okay to reply with ``400 Bad806Request`` in that situation, but sometimes that won't do and the code has807to continue working.808809You may still want to log that something fishy happened.  This is where810loggers come in handy.  As of Flask 0.3 a logger is preconfigured for you811to use.812813Here are some example log calls::814815    app.logger.debug('A value for debugging')816    app.logger.warning('A warning occurred (%d apples)', 42)817    app.logger.error('An error occurred')818819The attached :attr:`~flask.Flask.logger` is a standard logging820:class:`~logging.Logger`, so head over to the official `logging821documentation <http://docs.python.org/library/logging.html>`_ for more822information.823824Hooking in WSGI Middlewares825---------------------------826827If you want to add a WSGI middleware to your application you can wrap the828internal WSGI application.  For example if you want to use one of the829middlewares from the Werkzeug package to work around bugs in lighttpd, you830can do it like this::831832    from werkzeug.contrib.fixers import LighttpdCGIRootFix833    app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)834835.. _quickstart_deployment:836837Deploying to a Web Server838-------------------------839840Ready to deploy your new Flask app?  To wrap up the quickstart, you can841immediately deploy to a hosted platform, all of which offer a free plan for842small projects:843844- `Deploying Flask on Heroku <http://devcenter.heroku.com/articles/python>`_845- `Deploying WSGI on dotCloud <http://docs.dotcloud.com/services/python/>`_846  with `Flask-specific notes <http://flask.pocoo.org/snippets/48/>`_847848Other places where you can host your Flask app:849850- `Deploying Flask on Webfaction <http://flask.pocoo.org/snippets/65/>`_851- `Deploying Flask on Google App Engine <https://github.com/kamalgill/flask-appengine-template>`_852- `Sharing your Localhost Server with Localtunnel <http://flask.pocoo.org/snippets/89/>`_853854If you manage your own hosts and would like to host yourself, see the chapter855on :ref:`deployment`.