Skip to content
Myr

quickstart.rst

This file

Path

docs/quickstart.rst

851 lines · 31.1 KiB

Last changed by

Tighten quickstart deployment docs.Ron DuPlainbefore adoption3bf1750

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.  The first argument is the name of42   the application's module.  If you are using a single module (as in this43   example), you should use `__name__` because depending on if it's started as44   application or imported as module the name will be different (``'__main__'``45   versus the actual import name).  For more information, have a look at the46   :class:`~flask.Flask` documentation.472. Next we create an instance of this class.  We pass it the name of the module48   or package.  This is needed so that Flask knows where to look for templates,49   static files, and so on.503. We then use the :meth:`~flask.Flask.route` decorator to tell Flask what URL51   should trigger our function.524. The function is given a name which is also used to generate URLs for that53   particular function, and returns the message we want to display in the54   user's browser.555. Finally we use the :meth:`~flask.Flask.run` function to run the local server56   with our application.  The ``if __name__ == '__main__':`` makes sure the57   server only runs if the script is executed directly from the Python58   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 all public IPs.787980.. _debug-mode:8182Debug Mode83----------8485The :meth:`~flask.Flask.run` method is nice to start a local86development server, but you would have to restart it manually after each87change to your code.  That is not very nice and Flask can do better.  If88you enable debug support the server will reload itself on code changes,89and it will also provide you with a helpful debugger if things go wrong.9091There are two ways to enable debugging.  Either set that flag on the92application object::9394    app.debug = True95    app.run()9697Or pass it as a parameter to run::9899    app.run(debug=True)100101Both methods have the exact same effect.102103.. admonition:: Attention104105   Even though the interactive debugger does not work in forking environments106   (which makes it nearly impossible to use on production servers), it still107   allows the execution of arbitrary code. This makes it a major security risk108   and therefore it **must never be used on production machines**.109110Screenshot of the debugger in action:111112.. image:: _static/debugger.png113   :align: center114   :class: screenshot115   :alt: screenshot of debugger in action116117Have another debugger in mind? See :ref:`working-with-debuggers`.118119120Routing121-------122123Modern web applications have beautiful URLs.  This helps people remember124the URLs, which is especially handy for applications that are used from125mobile devices with slower network connections.  If the user can directly126go to the desired page without having to hit the index page it is more127likely they will like the page and come back next time.128129As you have seen above, the :meth:`~flask.Flask.route` decorator is used to130bind a function to a URL.  Here are some basic examples::131132    @app.route('/')133    def index():134        return 'Index Page'135136    @app.route('/hello')137    def hello():138        return 'Hello World'139140But there is more to it!  You can make certain parts of the URL dynamic and141attach multiple rules to a function.142143Variable Rules144``````````````145146To add variable parts to a URL you can mark these special sections as147``<variable_name>``.  Such a part is then passed as keyword argument to your148function.  Optionally a converter can be specified by specifying a rule with149``<converter:variable_name>``.  Here are some nice examples::150151    @app.route('/user/<username>')152    def show_user_profile(username):153        # show the user profile for that user154        return 'User %s' % username155156    @app.route('/post/<int:post_id>')157    def show_post(post_id):158        # show the post with the given id, the id is an integer159        return 'Post %d' % post_id160161The following converters exist:162163=========== ===========================================164`int`       accepts integers165`float`     like `int` but for floating point values166`path`      like the default but also accepts slashes167=========== ===========================================168169.. admonition:: Unique URLs / Redirection Behaviour170171   Flask's URL rules are based on Werkzeug's routing module.  The idea172   behind that module is to ensure beautiful and unique URLs based on173   precedents laid down by Apache and earlier HTTP servers.174175   Take these two rules::176177        @app.route('/projects/')178        def projects():179            return 'The project page'180181        @app.route('/about')182        def about():183            return 'The about page'184185   Though they look rather similar, they differ in their use of the trailing186   slash in the URL *definition*.  In the first case, the canonical URL for the187   `projects` endpoint has a trailing slash.  In that sense, it is similar to188   a folder on a file system.  Accessing it without a trailing slash will cause189   Flask to redirect to the canonical URL with the trailing slash.190191   In the second case, however, the URL is defined without a trailing slash,192   rather like the pathname of a file on UNIX-like systems. Accessing the URL193   with a trailing slash will produce a 404 "Not Found" error.194195   This behavior allows relative URLs to continue working if users access the196   page when they forget a trailing slash, consistent with how with how Apache197   and other servers work.  Also, the URLs will stay unique, which helps search198   engines avoid indexing the same page twice.199200201.. _url-building:202203URL Building204````````````205206If it can match URLs, can Flask also generate them?  Of course it can.  To207build a URL to a specific function you can use the :func:`~flask.url_for`208function.  It accepts the name of the function as first argument and a number209of keyword arguments, each corresponding to the variable part of the URL rule.210Unknown variable parts are appended to the URL as query parameters.  Here are211some examples:212213>>> from flask import Flask, url_for214>>> app = Flask(__name__)215>>> @app.route('/')216... def index(): pass217...218>>> @app.route('/login')219... def login(): pass220...221>>> @app.route('/user/<username>')222... def profile(username): pass223...224>>> with app.test_request_context():225...  print url_for('index')226...  print url_for('login')227...  print url_for('login', next='/')228...  print url_for('profile', username='John Doe')229...230/231/login232/login?next=/233/user/John%20Doe234235(This also uses the :meth:`~flask.Flask.test_request_context` method, explained236below.  It tells Flask to behave as though it is handling a request, even237though we are interacting with it through a Python shell.  Have a look at the238explanation below. :ref:`context-locals`).239240Why would you want to build URLs instead of hard-coding them into your241templates?  There are three good reasons for 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    @app.route('/login', methods=['GET', 'POST'])262    def login():263        if request.method == 'POST':264            do_the_login()265        else:266            show_the_login_form()267268If `GET` is present, `HEAD` will be added automatically for you.  You269don't have to deal with that.  It will also make sure that `HEAD` requests270are handled as the `HTTP RFC`_ (the document describing the HTTP271protocol) demands, so you can completely ignore that part of the HTTP272specification.  Likewise, as of Flask 0.6, `OPTIONS` is implemented for you273automatically as well.274275You have no idea what an HTTP method is?  Worry not, here is a quick276introduction to HTTP methods and why they matter:277278The HTTP method (also often called "the verb") tells the server what the279clients wants to *do* with the requested page.  The following methods are280very common:281282`GET`283    The browser tells the server to just *get* the information stored on284    that page and send it.  This is probably the most common method.285286`HEAD`287    The browser tells the server to get the information, but it is only288    interested in the *headers*, not the content of the page.  An289    application is supposed to handle that as if a `GET` request was290    received but to not deliver the actual content.  In Flask you don't291    have to deal with that at all, the underlying Werkzeug library handles292    that for you.293294`POST`295    The browser tells the server that it wants to *post* some new296    information to that URL and that the server must ensure the data is297    stored and only stored once.  This is how HTML forms usually298    transmit data to the server.299300`PUT`301    Similar to `POST` but the server might trigger the store procedure302    multiple times by overwriting the old values more than once.  Now you303    might be asking why this is useful, but there are some good reasons304    to do it this way.  Consider that the connection is lost during305    transmission: in this situation a system between the browser and the306    server might receive the request safely a second time without breaking307    things.  With `POST` that would not be possible because it must only308    be triggered once.309310`DELETE`311    Remove the information at the given location.312313`OPTIONS`314    Provides a quick way for a client to figure out which methods are315    supported by this URL.  Starting with Flask 0.6, this is implemented316    for you automatically.317318Now the interesting part is that in HTML4 and XHTML1, the only methods a319form can submit to the server are `GET` and `POST`.  But with JavaScript320and future HTML standards you can use the other methods as well.  Furthermore321HTTP has become quite popular lately and browsers are no longer the only322clients that are using HTTP. For instance, many revision control system323use it.324325.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt326327Static Files328------------329330Dynamic web applications also need static files.  That's usually where331the CSS and JavaScript files are coming from.  Ideally your web server is332configured to serve them for you, but during development Flask can do that333as well.  Just create a folder called `static` in your package or next to334your module and it will be available at `/static` on the application.335336To generate URLs that part of the URL, use the special ``'static'`` URL337name::338339    url_for('static', filename='style.css')340341The file has to be stored on the filesystem as ``static/style.css``.342343Rendering Templates344-------------------345346Generating HTML from within Python is not fun, and actually pretty347cumbersome because you have to do the HTML escaping on your own to keep348the application secure.  Because of that Flask configures the `Jinja2349<http://jinja.pocoo.org/2/>`_ template engine for you automatically.350351To render a template you can use the :func:`~flask.render_template`352method.  All you have to do is provide the name of the template and the353variables you want to pass to the template engine as keyword arguments.354Here's a simple example of how to render a template::355356    from flask import render_template357358    @app.route('/hello/')359    @app.route('/hello/<name>')360    def hello(name=None):361        return render_template('hello.html', name=name)362363Flask will look for templates in the `templates` folder.  So if your364application is a module, this folder is next to that module, if it's a365package it's actually inside your package:366367**Case 1**: a module::368369    /application.py370    /templates371        /hello.html372373**Case 2**: a package::374375    /application376        /__init__.py377        /templates378            /hello.html379380For templates you can use the full power of Jinja2 templates.  Head over381to the the official `Jinja2 Template Documentation382<http://jinja.pocoo.org/2/documentation/templates>`_ for more information.383384Here is an example template:385386.. sourcecode:: html+jinja387388    <!doctype html>389    <title>Hello from Flask</title>390    {% if name %}391      <h1>Hello {{ name }}!</h1>392    {% else %}393      <h1>Hello World!</h1>394    {% endif %}395396Inside templates you also have access to the :class:`~flask.request`,397:class:`~flask.session` and :class:`~flask.g` [#]_ objects398as well as the :func:`~flask.get_flashed_messages` function.399400Templates are especially useful if inheritance is used.  If you want to401know how that works, head over to the :ref:`template-inheritance` pattern402documentation.  Basically template inheritance makes it possible to keep403certain elements on each page (like header, navigation and footer).404405Automatic escaping is enabled, so if `name` contains HTML it will be escaped406automatically.  If you can trust a variable and you know that it will be407safe HTML (for example because it came from a module that converts wiki408markup to HTML) you can mark it as safe by using the409:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the410template.  Head over to the Jinja 2 documentation for more examples.411412Here is a basic introduction to how the :class:`~jinja2.Markup` class works:413414>>> from flask import Markup415>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'416Markup(u'<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')417>>> Markup.escape('<blink>hacker</blink>')418Markup(u'&lt;blink&gt;hacker&lt;/blink&gt;')419>>> Markup('<em>Marked up</em> &raquo; HTML').striptags()420u'Marked up \xbb HTML'421422.. versionchanged:: 0.5423424   Autoescaping is no longer enabled for all templates.  The following425   extensions for templates trigger autoescaping: ``.html``, ``.htm``,426   ``.xml``, ``.xhtml``.  Templates loaded from a string will have427   autoescaping disabled.428429.. [#] Unsure what that :class:`~flask.g` object is? It's something in which430   you can store information for your own needs, check the documentation of431   that object (:class:`~flask.g`) and the :ref:`sqlite3` for more432   information.433434435Accessing Request Data436----------------------437438For web applications it's crucial to react to the data a client sent to439the server.  In Flask this information is provided by the global440:class:`~flask.request` object.  If you have some experience with Python441you might be wondering how that object can be global and how Flask442manages to still be threadsafe.  The answer is context locals:443444445.. _context-locals:446447Context Locals448``````````````449450.. admonition:: Insider Information451452   If you want to understand how that works and how you can implement453   tests with context locals, read this section, otherwise just skip it.454455Certain objects in Flask are global objects, but not of the usual kind.456These objects are actually proxies to objects that are local to a specific457context.  What a mouthful.  But that is actually quite easy to understand.458459Imagine the context being the handling thread.  A request comes in and the460web server decides to spawn a new thread (or something else, the461underlying object is capable of dealing with concurrency systems other462than threads).  When Flask starts its internal request handling it463figures out that the current thread is the active context and binds the464current application and the WSGI environments to that context (thread).465It does that in an intelligent way so that one application can invoke another466application without breaking.467468So what does this mean to you?  Basically you can completely ignore that469this is the case unless you are doing something like unit testing.  You470will notice that code which depends on a request object will suddenly break471because there is no request object.  The solution is creating a request472object yourself and binding it to the context.  The easiest solution for473unit testing is to use the :meth:`~flask.Flask.test_request_context`474context manager.  In combination with the `with` statement it will bind a475test request so that you can interact with it.  Here is an example::476477    from flask import request478479    with app.test_request_context('/hello', method='POST'):480        # now you can do something with the request until the481        # end of the with block, such as basic assertions:482        assert request.path == '/hello'483        assert request.method == 'POST'484485The other possibility is passing a whole WSGI environment to the486:meth:`~flask.Flask.request_context` method::487488    from flask import request489490    with app.request_context(environ):491        assert request.method == 'POST'492493The Request Object494``````````````````495496The request object is documented in the API section and we will not cover497it here in detail (see :class:`~flask.request`). Here is a broad overview of498some of the most common operations.  First of all you have to import it from499the `flask` module::500501    from flask import request502503The current request method is available by using the504:attr:`~flask.request.method` attribute.  To access form data (data505transmitted in a `POST` or `PUT` request) you can use the506:attr:`~flask.request.form` attribute.  Here is a full example of the two507attributes mentioned above::508509    @app.route('/login', methods=['POST', 'GET'])510    def login():511        error = None512        if request.method == 'POST':513            if valid_login(request.form['username'],514                           request.form['password']):515                return log_the_user_in(request.form['username'])516            else:517                error = 'Invalid username/password'518        # this is executed if the request method was GET or the519        # credentials were invalid520521What happens if the key does not exist in the `form` attribute?  In that522case a special :exc:`KeyError` is raised.  You can catch it like a523standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request524error page is shown instead.  So for many situations you don't have to525deal with that problem.526527To access parameters submitted in the URL (``?key=value``) you can use the528:attr:`~flask.request.args` attribute::529530    searchword = request.args.get('q', '')531532We recommend accessing URL parameters with `get` or by catching the533`KeyError` because users might change the URL and presenting them a 400534bad request page in that case is not user friendly.535536For a full list of methods and attributes of the request object, head over537to the :class:`~flask.request` documentation.538539540File Uploads541````````````542543You can handle uploaded files with Flask easily.  Just make sure not to544forget to set the ``enctype="multipart/form-data"`` attribute on your HTML545form, otherwise the browser will not transmit your files at all.546547Uploaded files are stored in memory or at a temporary location on the548filesystem.  You can access those files by looking at the549:attr:`~flask.request.files` attribute on the request object.  Each550uploaded file is stored in that dictionary.  It behaves just like a551standard Python :class:`file` object, but it also has a552:meth:`~werkzeug.datastructures.FileStorage.save` method that allows you to store that553file on the filesystem of the server.  Here is a simple example showing how554that works::555556    from flask import request557558    @app.route('/upload', methods=['GET', 'POST'])559    def upload_file():560        if request.method == 'POST':561            f = request.files['the_file']562            f.save('/var/www/uploads/uploaded_file.txt')563        ...564565If you want to know how the file was named on the client before it was566uploaded to your application, you can access the567:attr:`~werkzeug.datastructures.FileStorage.filename` attribute.  However please keep in568mind that this value can be forged so never ever trust that value.  If you569want to use the filename of the client to store the file on the server,570pass it through the :func:`~werkzeug.utils.secure_filename` function that571Werkzeug provides for you::572573    from flask import request574    from werkzeug import secure_filename575576    @app.route('/upload', methods=['GET', 'POST'])577    def upload_file():578        if request.method == 'POST':579            f = request.files['the_file']580            f.save('/var/www/uploads/' + secure_filename(f.filename))581        ...582583For some better examples, checkout the :ref:`uploading-files` pattern.584585Cookies586```````587588To access cookies you can use the :attr:`~flask.Request.cookies`589attribute.  To set cookies you can use the590:attr:`~flask.Response.set_cookie` method of response objects.  The591:attr:`~flask.Request.cookies` attribute of request objects is a592dictionary with all the cookies the client transmits.  If you want to use593sessions, do not use the cookies directly but instead use the594:ref:`sessions` in Flask that add some security on top of cookies for you.595596Reading cookies::597598    from flask import request599600    @app.route('/')601    def index():602        username = request.cookies.get('username')603        # use cookies.get(key) instead of cookies[key] to not get a604        # KeyError if the cookie is missing.605606Storing cookies::607608    from flask import make_response609610    @app.route('/')611    def index():612        resp = make_response(render_template(...))613        resp.set_cookie('username', 'the username')614        return resp615616Note that cookies are set on response objects.  Since you normally617just return strings from the view functions Flask will convert them into618response objects for you.  If you explicitly want to do that you can use619the :meth:`~flask.make_response` function and then modify it.620621Sometimes you might want to set a cookie at a point where the response622object does not exist yet.  This is possible by utilizing the623:ref:`deferred-callbacks` pattern.624625For this also see :ref:`about-responses`.626627Redirects and Errors628--------------------629630To redirect a user to somewhere else you can use the631:func:`~flask.redirect` function. To abort a request early with an error632code use the :func:`~flask.abort` function.  Here an example how this works::633634    from flask import abort, redirect, url_for635636    @app.route('/')637    def index():638        return redirect(url_for('login'))639640    @app.route('/login')641    def login():642        abort(401)643        this_is_never_executed()644645This is a rather pointless example because a user will be redirected from646the index to a page they cannot access (401 means access denied) but it647shows how that works.648649By default a black and white error page is shown for each error code.  If650you want to customize the error page, you can use the651:meth:`~flask.Flask.errorhandler` decorator::652653    from flask import render_template654655    @app.errorhandler(404)656    def page_not_found(error):657        return render_template('page_not_found.html'), 404658659Note the ``404`` after the :func:`~flask.render_template` call.  This660tells Flask that the status code of that page should be 404 which means661not found.  By default 200 is assumed which translates to: all went well.662663.. _about-responses:664665About Responses666---------------667668The return value from a view function is automatically converted into a669response object for you.  If the return value is a string it's converted670into a response object with the string as response body, an ``200 OK``671error code and a ``text/html`` mimetype.  The logic that Flask applies to672converting return values into response objects is as follows:6736741.  If a response object of the correct type is returned it's directly675    returned from the view.6762.  If it's a string, a response object is created with that data and the677    default parameters.6783.  If a tuple is returned the response object is created by passing the679    tuple as arguments to the response object's constructor.6804.  If none of that works, Flask will assume the return value is a681    valid WSGI application and convert that into a response object.682683If you want to get hold of the resulting response object inside the view684you can use the :func:`~flask.make_response` function.685686Imagine you have a view like this:687688.. sourcecode:: python689690    @app.errorhandler(404)691    def not_found(error):692        return render_template('error.html'), 404693694You just need to wrap the return expression with695:func:`~flask.make_response` and get the result object to modify it, then696return it:697698.. sourcecode:: python699700    @app.errorhandler(404)701    def not_found(error):702        resp = make_response(render_template('error.html'), 404)703        resp.headers['X-Something'] = 'A value'704        return resp705706.. _sessions:707708Sessions709--------710711In addition to the request object there is also a second object called712:class:`~flask.session` which allows you to store information specific to a713user from one request to the next.  This is implemented on top of cookies714for you and signs the cookies cryptographically.  What this means is that715the user could look at the contents of your cookie but not modify it,716unless they know the secret key used for signing.717718In order to use sessions you have to set a secret key.  Here is how719sessions work::720721    from flask import Flask, session, redirect, url_for, escape, request722723    app = Flask(__name__)724725    @app.route('/')726    def index():727        if 'username' in session:728            return 'Logged in as %s' % escape(session['username'])729        return 'You are not logged in'730731    @app.route('/login', methods=['GET', 'POST'])732    def login():733        if request.method == 'POST':734            session['username'] = request.form['username']735            return redirect(url_for('index'))736        return '''737            <form action="" method="post">738                <p><input type=text name=username>739                <p><input type=submit value=Login>740            </form>741        '''742743    @app.route('/logout')744    def logout():745        # remove the username from the session if its there746        session.pop('username', None)747        return redirect(url_for('index'))748749    # set the secret key.  keep this really secret:750    app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'751752The :func:`~flask.escape` mentioned here does escaping for you if you are753not using the template engine (as in this example).754755.. admonition:: How to generate good secret keys756757   The problem with random is that it's hard to judge what is truly random.  And758   a secret key should be as random as possible.  Your operating system759   has ways to generate pretty random stuff based on a cryptographic760   random generator which can be used to get such a key:761762   >>> import os763   >>> os.urandom(24)764   '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'765766   Just take that thing and copy/paste it into your code and you're done.767768A note on cookie-based sessions: Flask will take the values you put into the769session object and serialize them into a cookie.  If you are finding some770values do not persist across requests, cookies are indeed enabled, and you are771not getting a clear error message, check the size of the cookie in your page772responses compared to the size supported by web browsers.773774775Message Flashing776----------------777778Good applications and user interfaces are all about feedback.  If the user779does not get enough feedback they will probably end up hating the780application.  Flask provides a really simple way to give feedback to a781user with the flashing system.  The flashing system basically makes it782possible to record a message at the end of a request and access it on the next783(and only the next) request.  This is usually combined with a layout784template to expose the message.785786To flash a message use the :func:`~flask.flash` method, to get hold of the787messages you can use :func:`~flask.get_flashed_messages` which is also788available in the templates.  Check out the :ref:`message-flashing-pattern`789for a full example.790791Logging792-------793794.. versionadded:: 0.3795796Sometimes you might be in a situation where you deal with data that797should be correct, but actually is not.  For example you may have some client-side798code that sends an HTTP request to the server but it's obviously799malformed.  This might be caused by a user tampering with the data, or the800client code failing.  Most of the time it's okay to reply with ``400 Bad801Request`` in that situation, but sometimes that won't do and the code has802to continue working.803804You may still want to log that something fishy happened.  This is where805loggers come in handy.  As of Flask 0.3 a logger is preconfigured for you806to use.807808Here are some example log calls::809810    app.logger.debug('A value for debugging')811    app.logger.warning('A warning occurred (%d apples)', 42)812    app.logger.error('An error occurred')813814The attached :attr:`~flask.Flask.logger` is a standard logging815:class:`~logging.Logger`, so head over to the official `logging816documentation <http://docs.python.org/library/logging.html>`_ for more817information.818819Hooking in WSGI Middlewares820---------------------------821822If you want to add a WSGI middleware to your application you can wrap the823internal WSGI application.  For example if you want to use one of the824middlewares from the Werkzeug package to work around bugs in lighttpd, you825can do it like this::826827    from werkzeug.contrib.fixers import LighttpdCGIRootFix828    app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)829830.. _quickstart_deployment:831832Deploying to a Web Server833-------------------------834835Ready to deploy your new Flask app?  To wrap up the quickstart, you can836immediately deploy to a hosted platform, all of which offer a free plan for837small projects:838839- `Deploying Flask on Heroku <http://devcenter.heroku.com/articles/python>`_840- `Deploying Flask on ep.io <https://www.ep.io/docs/quickstart/flask/>`_841- `Deploying WSGI on dotCloud <http://docs.dotcloud.com/services/python/>`_842  with `Flask-specific notes <http://flask.pocoo.org/snippets/48/>`_843844Other places where you can host your Flask app:845846- `Deploying Flask on Webfaction <http://flask.pocoo.org/snippets/65/>`_847- `Deploying Flask on Google App Engine <https://github.com/kamalgill/flask-appengine-template>`_848- `Sharing your Localhost Server with Localtunnel <http://flask.pocoo.org/snippets/89/>`_849850If you manage your own hosts and would like to host yourself, see the chapter851on :ref:`deployment`.