quickstart.rst
This file
Path
docs/quickstart.rst
893 lines · 32.8 KiB
Last changed by
Merge pull request #1183 from k-funk/patch-1Markus Unterwaditzerbefore adoption2401e21
History of this fileTake 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!'2223Just save it as `hello.py` (or something similar) and run it with your Python24interpreter. Make sure to not call your application `flask.py` because this25would conflict with Flask itself.2627To run the application you can either use the ``flask`` command or28python's ``-m`` switch with Flask::2930 $ flask -a hello run31 * Running on http://127.0.0.1:5000/3233or alternatively::3435 $ python -m flask -a hello run36 * Running on http://127.0.0.1:5000/3738Now head over to `http://127.0.0.1:5000/ <http://127.0.0.1:5000/>`_, and you39should see your hello world greeting.4041So what did that code do?42431. First we imported the :class:`~flask.Flask` class. An instance of this44 class will be our WSGI application.452. Next we create an instance of this class. The first argument is the name of46 the application's module or package. If you are using a single module (as47 in this example), you should use `__name__` because depending on if it's48 started as application or imported as module the name will be different49 (``'__main__'`` versus the actual import name). This is needed so that50 Flask knows where to look for templates, static files, and so on. For more51 information have a look at the :class:`~flask.Flask` documentation.523. We then use the :meth:`~flask.Flask.route` decorator to tell Flask what URL53 should trigger our function.544. The function is given a name which is also used to generate URLs for that55 particular function, and returns the message we want to display in the56 user's browser.575. Finally we use the Flask development server to run the local server58 with our application.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 the debugger disabled or trust the users on your network,72 you can make the server publicly available simply by adding73 ``--host=0.0.0.0`` to the command line::7475 flask -a hello run --host=0.0.0.07677 This tells your operating system to listen on all public IPs.7879What to do if the Server does not Start80---------------------------------------8182In case the ``python -m flask`` fails or ``flask`` does not exist,83there are multiple reasons this might be the case. First of all you need84to look at the error message.8586Old Version of Flask87````````````````````8889Versions of Flask older than 1.0 use to have different ways to start the90application. In short, the ``flask`` command did not exist, and91neither did ``python -m flask``. In that case you have two options:92either upgrade to newer Flask versions or have a look at the :ref:`server`93docs to see the alternative method for running a server.9495Python older 2.796````````````````9798In case you have a version of Python older than 2.7 ``python -m flask``99does not work. You can either use ``flask`` or ``python -m100flask.cli`` as an alternative. This is because Python before 2.7 does no101permit packages to act as executable modules. For more information see102:ref:`cli`.103104Invalid Import Name105```````````````````106107The ``-a`` argument to ``flask`` is the name of the module to import. In108case that module is incorrectly named you will get an import error upon109start (or if debug is enabled when you navigate to the application). It110will tell you what it tried to import and why it failed.111112The most common reason is a typo or because you did not actually create an113``app`` object.114115.. _debug-mode:116117Debug Mode118----------119120The ``flask`` script is nice to start a local development server, but121you would have to restart it manually after each change to your code.122That is not very nice and Flask can do better. If you enable debug123support the server will reload itself on code changes, and it will also124provide you with a helpful debugger if things go wrong.125126There are different ways to enable the debug mode. The most obvious one127is the ``--debug`` parameter to the ``flask`` command::128129 flask --debug -a hello run130131This does the following things:1321331. it activates the debugger1342. it activates the automatic reloader1353. it enables the debug mode on the Flask application.136137There are more parameters that are explained in the :ref:`server` docs.138139.. admonition:: Attention140141 Even though the interactive debugger does not work in forking environments142 (which makes it nearly impossible to use on production servers), it still143 allows the execution of arbitrary code. This makes it a major security risk144 and therefore it **must never be used on production machines**.145146Screenshot of the debugger in action:147148.. image:: _static/debugger.png149 :align: center150 :class: screenshot151 :alt: screenshot of debugger in action152153Have another debugger in mind? See :ref:`working-with-debuggers`.154155156Routing157-------158159Modern web applications have beautiful URLs. This helps people remember160the URLs, which is especially handy for applications that are used from161mobile devices with slower network connections. If the user can directly162go to the desired page without having to hit the index page it is more163likely they will like the page and come back next time.164165As you have seen above, the :meth:`~flask.Flask.route` decorator is used to166bind a function to a URL. Here are some basic examples::167168 @app.route('/')169 def index():170 return 'Index Page'171172 @app.route('/hello')173 def hello():174 return 'Hello World'175176But there is more to it! You can make certain parts of the URL dynamic and177attach multiple rules to a function.178179Variable Rules180``````````````181182To add variable parts to a URL you can mark these special sections as183``<variable_name>``. Such a part is then passed as a keyword argument to your184function. Optionally a converter can be used by specifying a rule with185``<converter:variable_name>``. Here are some nice examples::186187 @app.route('/user/<username>')188 def show_user_profile(username):189 # show the user profile for that user190 return 'User %s' % username191192 @app.route('/post/<int:post_id>')193 def show_post(post_id):194 # show the post with the given id, the id is an integer195 return 'Post %d' % post_id196197The following converters exist:198199=========== ===============================================200`string` accepts any text without a slash (the default)201`int` accepts integers202`float` like `int` but for floating point values203`path` like the default but also accepts slashes204=========== ===============================================205206.. admonition:: Unique URLs / Redirection Behavior207208 Flask's URL rules are based on Werkzeug's routing module. The idea209 behind that module is to ensure beautiful and unique URLs based on210 precedents laid down by Apache and earlier HTTP servers.211212 Take these two rules::213214 @app.route('/projects/')215 def projects():216 return 'The project page'217218 @app.route('/about')219 def about():220 return 'The about page'221222 Though they look rather similar, they differ in their use of the trailing223 slash in the URL *definition*. In the first case, the canonical URL for the224 `projects` endpoint has a trailing slash. In that sense, it is similar to225 a folder on a file system. Accessing it without a trailing slash will cause226 Flask to redirect to the canonical URL with the trailing slash.227228 In the second case, however, the URL is defined without a trailing slash,229 rather like the pathname of a file on UNIX-like systems. Accessing the URL230 with a trailing slash will produce a 404 "Not Found" error.231232 This behavior allows relative URLs to continue working even if the trailing233 slash is omitted, consistent with how Apache and other servers work. Also,234 the URLs will stay unique, which helps search engines avoid indexing the235 same page twice.236237238.. _url-building:239240URL Building241````````````242243If it can match URLs, can Flask also generate them? Of course it can. To244build a URL to a specific function you can use the :func:`~flask.url_for`245function. It accepts the name of the function as first argument and a number246of keyword arguments, each corresponding to the variable part of the URL rule.247Unknown variable parts are appended to the URL as query parameters. Here are248some examples:249250>>> from flask import Flask, url_for251>>> app = Flask(__name__)252>>> @app.route('/')253... def index(): pass254...255>>> @app.route('/login')256... def login(): pass257...258>>> @app.route('/user/<username>')259... def profile(username): pass260...261>>> with app.test_request_context():262... print url_for('index')263... print url_for('login')264... print url_for('login', next='/')265... print url_for('profile', username='John Doe')266...267/268/login269/login?next=/270/user/John%20Doe271272(This also uses the :meth:`~flask.Flask.test_request_context` method, explained273below. It tells Flask to behave as though it is handling a request, even274though we are interacting with it through a Python shell. Have a look at the275explanation below. :ref:`context-locals`).276277Why would you want to build URLs using the URL reversing function278:func:`~flask.url_for` instead of hard-coding them into your templates?279There are three good reasons for this:2802811. Reversing is often more descriptive than hard-coding the URLs. More282 importantly, it allows you to change URLs in one go, without having to283 remember to change URLs all over the place.2842. URL building will handle escaping of special characters and Unicode285 data transparently for you, so you don't have to deal with them.2863. If your application is placed outside the URL root (say, in287 ``/myapplication`` instead of ``/``), :func:`~flask.url_for` will handle288 that properly for you.289290291HTTP Methods292````````````293294HTTP (the protocol web applications are speaking) knows different methods for295accessing URLs. By default, a route only answers to `GET` requests, but that296can be changed by providing the `methods` argument to the297:meth:`~flask.Flask.route` decorator. Here are some examples::298299 from flask import request300301 @app.route('/login', methods=['GET', 'POST'])302 def login():303 if request.method == 'POST':304 do_the_login()305 else:306 show_the_login_form()307308If `GET` is present, `HEAD` will be added automatically for you. You309don't have to deal with that. It will also make sure that `HEAD` requests310are handled as the `HTTP RFC`_ (the document describing the HTTP311protocol) demands, so you can completely ignore that part of the HTTP312specification. Likewise, as of Flask 0.6, `OPTIONS` is implemented for you313automatically as well.314315You have no idea what an HTTP method is? Worry not, here is a quick316introduction to HTTP methods and why they matter:317318The HTTP method (also often called "the verb") tells the server what the319clients wants to *do* with the requested page. The following methods are320very common:321322`GET`323 The browser tells the server to just *get* the information stored on324 that page and send it. This is probably the most common method.325326`HEAD`327 The browser tells the server to get the information, but it is only328 interested in the *headers*, not the content of the page. An329 application is supposed to handle that as if a `GET` request was330 received but to not deliver the actual content. In Flask you don't331 have to deal with that at all, the underlying Werkzeug library handles332 that for you.333334`POST`335 The browser tells the server that it wants to *post* some new336 information to that URL and that the server must ensure the data is337 stored and only stored once. This is how HTML forms usually338 transmit data to the server.339340`PUT`341 Similar to `POST` but the server might trigger the store procedure342 multiple times by overwriting the old values more than once. Now you343 might be asking why this is useful, but there are some good reasons344 to do it this way. Consider that the connection is lost during345 transmission: in this situation a system between the browser and the346 server might receive the request safely a second time without breaking347 things. With `POST` that would not be possible because it must only348 be triggered once.349350`DELETE`351 Remove the information at the given location.352353`OPTIONS`354 Provides a quick way for a client to figure out which methods are355 supported by this URL. Starting with Flask 0.6, this is implemented356 for you automatically.357358Now the interesting part is that in HTML4 and XHTML1, the only methods a359form can submit to the server are `GET` and `POST`. But with JavaScript360and future HTML standards you can use the other methods as well. Furthermore361HTTP has become quite popular lately and browsers are no longer the only362clients that are using HTTP. For instance, many revision control systems363use it.364365.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt366367Static Files368------------369370Dynamic web applications also need static files. That's usually where371the CSS and JavaScript files are coming from. Ideally your web server is372configured to serve them for you, but during development Flask can do that373as well. Just create a folder called `static` in your package or next to374your module and it will be available at `/static` on the application.375376To generate URLs for static files, use the special ``'static'`` endpoint name::377378 url_for('static', filename='style.css')379380The file has to be stored on the filesystem as ``static/style.css``.381382Rendering Templates383-------------------384385Generating HTML from within Python is not fun, and actually pretty386cumbersome because you have to do the HTML escaping on your own to keep387the application secure. Because of that Flask configures the `Jinja2388<http://jinja.pocoo.org/>`_ template engine for you automatically.389390To render a template you can use the :func:`~flask.render_template`391method. All you have to do is provide the name of the template and the392variables you want to pass to the template engine as keyword arguments.393Here's a simple example of how to render a template::394395 from flask import render_template396397 @app.route('/hello/')398 @app.route('/hello/<name>')399 def hello(name=None):400 return render_template('hello.html', name=name)401402Flask will look for templates in the `templates` folder. So if your403application is a module, this folder is next to that module, if it's a404package it's actually inside your package:405406**Case 1**: a module::407408 /application.py409 /templates410 /hello.html411412**Case 2**: a package::413414 /application415 /__init__.py416 /templates417 /hello.html418419For templates you can use the full power of Jinja2 templates. Head over420to the official `Jinja2 Template Documentation421<http://jinja.pocoo.org/docs/templates>`_ for more information.422423Here is an example template:424425.. sourcecode:: html+jinja426427 <!doctype html>428 <title>Hello from Flask</title>429 {% if name %}430 <h1>Hello {{ name }}!</h1>431 {% else %}432 <h1>Hello World!</h1>433 {% endif %}434435Inside templates you also have access to the :class:`~flask.request`,436:class:`~flask.session` and :class:`~flask.g` [#]_ objects437as well as the :func:`~flask.get_flashed_messages` function.438439Templates are especially useful if inheritance is used. If you want to440know how that works, head over to the :ref:`template-inheritance` pattern441documentation. Basically template inheritance makes it possible to keep442certain elements on each page (like header, navigation and footer).443444Automatic escaping is enabled, so if `name` contains HTML it will be escaped445automatically. If you can trust a variable and you know that it will be446safe HTML (for example because it came from a module that converts wiki447markup to HTML) you can mark it as safe by using the448:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the449template. Head over to the Jinja 2 documentation for more examples.450451Here is a basic introduction to how the :class:`~jinja2.Markup` class works:452453>>> from flask import Markup454>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'455Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')456>>> Markup.escape('<blink>hacker</blink>')457Markup(u'<blink>hacker</blink>')458>>> Markup('<em>Marked up</em> » HTML').striptags()459u'Marked up \xbb HTML'460461.. versionchanged:: 0.5462463 Autoescaping is no longer enabled for all templates. The following464 extensions for templates trigger autoescaping: ``.html``, ``.htm``,465 ``.xml``, ``.xhtml``. Templates loaded from a string will have466 autoescaping disabled.467468.. [#] Unsure what that :class:`~flask.g` object is? It's something in which469 you can store information for your own needs, check the documentation of470 that object (:class:`~flask.g`) and the :ref:`sqlite3` for more471 information.472473474Accessing Request Data475----------------------476477For web applications it's crucial to react to the data a client sent to478the server. In Flask this information is provided by the global479:class:`~flask.request` object. If you have some experience with Python480you might be wondering how that object can be global and how Flask481manages to still be threadsafe. The answer is context locals:482483484.. _context-locals:485486Context Locals487``````````````488489.. admonition:: Insider Information490491 If you want to understand how that works and how you can implement492 tests with context locals, read this section, otherwise just skip it.493494Certain objects in Flask are global objects, but not of the usual kind.495These objects are actually proxies to objects that are local to a specific496context. What a mouthful. But that is actually quite easy to understand.497498Imagine the context being the handling thread. A request comes in and the499web server decides to spawn a new thread (or something else, the500underlying object is capable of dealing with concurrency systems other501than threads). When Flask starts its internal request handling it502figures out that the current thread is the active context and binds the503current application and the WSGI environments to that context (thread).504It does that in an intelligent way so that one application can invoke another505application without breaking.506507So what does this mean to you? Basically you can completely ignore that508this is the case unless you are doing something like unit testing. You509will notice that code which depends on a request object will suddenly break510because there is no request object. The solution is creating a request511object yourself and binding it to the context. The easiest solution for512unit testing is to use the :meth:`~flask.Flask.test_request_context`513context manager. In combination with the `with` statement it will bind a514test request so that you can interact with it. Here is an example::515516 from flask import request517518 with app.test_request_context('/hello', method='POST'):519 # now you can do something with the request until the520 # end of the with block, such as basic assertions:521 assert request.path == '/hello'522 assert request.method == 'POST'523524The other possibility is passing a whole WSGI environment to the525:meth:`~flask.Flask.request_context` method::526527 from flask import request528529 with app.request_context(environ):530 assert request.method == 'POST'531532The Request Object533``````````````````534535The request object is documented in the API section and we will not cover536it here in detail (see :class:`~flask.request`). Here is a broad overview of537some of the most common operations. First of all you have to import it from538the `flask` module::539540 from flask import request541542The current request method is available by using the543:attr:`~flask.request.method` attribute. To access form data (data544transmitted in a `POST` or `PUT` request) you can use the545:attr:`~flask.request.form` attribute. Here is a full example of the two546attributes mentioned above::547548 @app.route('/login', methods=['POST', 'GET'])549 def login():550 error = None551 if request.method == 'POST':552 if valid_login(request.form['username'],553 request.form['password']):554 return log_the_user_in(request.form['username'])555 else:556 error = 'Invalid username/password'557 # the code below is executed if the request method558 # was GET or the credentials were invalid559 return render_template('login.html', error=error)560561What happens if the key does not exist in the `form` attribute? In that562case a special :exc:`KeyError` is raised. You can catch it like a563standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request564error page is shown instead. So for many situations you don't have to565deal with that problem.566567To access parameters submitted in the URL (``?key=value``) you can use the568:attr:`~flask.request.args` attribute::569570 searchword = request.args.get('key', '')571572We recommend accessing URL parameters with `get` or by catching the573`KeyError` because users might change the URL and presenting them a 400574bad request page in that case is not user friendly.575576For a full list of methods and attributes of the request object, head over577to the :class:`~flask.request` documentation.578579580File Uploads581````````````582583You can handle uploaded files with Flask easily. Just make sure not to584forget to set the ``enctype="multipart/form-data"`` attribute on your HTML585form, otherwise the browser will not transmit your files at all.586587Uploaded files are stored in memory or at a temporary location on the588filesystem. You can access those files by looking at the589:attr:`~flask.request.files` attribute on the request object. Each590uploaded file is stored in that dictionary. It behaves just like a591standard Python :class:`file` object, but it also has a592:meth:`~werkzeug.datastructures.FileStorage.save` method that allows you to store that593file on the filesystem of the server. Here is a simple example showing how594that works::595596 from flask import request597598 @app.route('/upload', methods=['GET', 'POST'])599 def upload_file():600 if request.method == 'POST':601 f = request.files['the_file']602 f.save('/var/www/uploads/uploaded_file.txt')603 ...604605If you want to know how the file was named on the client before it was606uploaded to your application, you can access the607:attr:`~werkzeug.datastructures.FileStorage.filename` attribute. However please keep in608mind that this value can be forged so never ever trust that value. If you609want to use the filename of the client to store the file on the server,610pass it through the :func:`~werkzeug.utils.secure_filename` function that611Werkzeug provides for you::612613 from flask import request614 from werkzeug import secure_filename615616 @app.route('/upload', methods=['GET', 'POST'])617 def upload_file():618 if request.method == 'POST':619 f = request.files['the_file']620 f.save('/var/www/uploads/' + secure_filename(f.filename))621 ...622623For some better examples, checkout the :ref:`uploading-files` pattern.624625Cookies626```````627628To access cookies you can use the :attr:`~flask.Request.cookies`629attribute. To set cookies you can use the630:attr:`~flask.Response.set_cookie` method of response objects. The631:attr:`~flask.Request.cookies` attribute of request objects is a632dictionary with all the cookies the client transmits. If you want to use633sessions, do not use the cookies directly but instead use the634:ref:`sessions` in Flask that add some security on top of cookies for you.635636Reading cookies::637638 from flask import request639640 @app.route('/')641 def index():642 username = request.cookies.get('username')643 # use cookies.get(key) instead of cookies[key] to not get a644 # KeyError if the cookie is missing.645646Storing cookies::647648 from flask import make_response649650 @app.route('/')651 def index():652 resp = make_response(render_template(...))653 resp.set_cookie('username', 'the username')654 return resp655656Note that cookies are set on response objects. Since you normally657just return strings from the view functions Flask will convert them into658response objects for you. If you explicitly want to do that you can use659the :meth:`~flask.make_response` function and then modify it.660661Sometimes you might want to set a cookie at a point where the response662object does not exist yet. This is possible by utilizing the663:ref:`deferred-callbacks` pattern.664665For this also see :ref:`about-responses`.666667Redirects and Errors668--------------------669670To redirect a user to another endpoint, use the :func:`~flask.redirect`671function; to abort a request early with an error code, use the672:func:`~flask.abort` function::673674 from flask import abort, redirect, url_for675676 @app.route('/')677 def index():678 return redirect(url_for('login'))679680 @app.route('/login')681 def login():682 abort(401)683 this_is_never_executed()684685This is a rather pointless example because a user will be redirected from686the index to a page they cannot access (401 means access denied) but it687shows how that works.688689By default a black and white error page is shown for each error code. If690you want to customize the error page, you can use the691:meth:`~flask.Flask.errorhandler` decorator::692693 from flask import render_template694695 @app.errorhandler(404)696 def page_not_found(error):697 return render_template('page_not_found.html'), 404698699Note the ``404`` after the :func:`~flask.render_template` call. This700tells Flask that the status code of that page should be 404 which means701not found. By default 200 is assumed which translates to: all went well.702703.. _about-responses:704705About Responses706---------------707708The return value from a view function is automatically converted into a709response object for you. If the return value is a string it's converted710into a response object with the string as response body, a ``200 OK``711status code and a ``text/html`` mimetype. The logic that Flask applies to712converting return values into response objects is as follows:7137141. If a response object of the correct type is returned it's directly715 returned from the view.7162. If it's a string, a response object is created with that data and the717 default parameters.7183. If a tuple is returned the items in the tuple can provide extra719 information. Such tuples have to be in the form ``(response, status,720 headers)`` or ``(response, headers)`` where at least one item has721 to be in the tuple. The `status` value will override the status code722 and `headers` can be a list or dictionary of additional header values.7234. If none of that works, Flask will assume the return value is a724 valid WSGI application and convert that into a response object.725726If you want to get hold of the resulting response object inside the view727you can use the :func:`~flask.make_response` function.728729Imagine you have a view like this:730731.. sourcecode:: python732733 @app.errorhandler(404)734 def not_found(error):735 return render_template('error.html'), 404736737You just need to wrap the return expression with738:func:`~flask.make_response` and get the response object to modify it, then739return it:740741.. sourcecode:: python742743 @app.errorhandler(404)744 def not_found(error):745 resp = make_response(render_template('error.html'), 404)746 resp.headers['X-Something'] = 'A value'747 return resp748749.. _sessions:750751Sessions752--------753754In addition to the request object there is also a second object called755:class:`~flask.session` which allows you to store information specific to a756user from one request to the next. This is implemented on top of cookies757for you and signs the cookies cryptographically. What this means is that758the user could look at the contents of your cookie but not modify it,759unless they know the secret key used for signing.760761In order to use sessions you have to set a secret key. Here is how762sessions work::763764 from flask import Flask, session, redirect, url_for, escape, request765766 app = Flask(__name__)767768 @app.route('/')769 def index():770 if 'username' in session:771 return 'Logged in as %s' % escape(session['username'])772 return 'You are not logged in'773774 @app.route('/login', methods=['GET', 'POST'])775 def login():776 if request.method == 'POST':777 session['username'] = request.form['username']778 return redirect(url_for('index'))779 return '''780 <form action="" method="post">781 <p><input type=text name=username>782 <p><input type=submit value=Login>783 </form>784 '''785786 @app.route('/logout')787 def logout():788 # remove the username from the session if it's there789 session.pop('username', None)790 return redirect(url_for('index'))791792 # set the secret key. keep this really secret:793 app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'794795The :func:`~flask.escape` mentioned here does escaping for you if you are796not using the template engine (as in this example).797798.. admonition:: How to generate good secret keys799800 The problem with random is that it's hard to judge what is truly random. And801 a secret key should be as random as possible. Your operating system802 has ways to generate pretty random stuff based on a cryptographic803 random generator which can be used to get such a key:804805 >>> import os806 >>> os.urandom(24)807 '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'808809 Just take that thing and copy/paste it into your code and you're done.810811A note on cookie-based sessions: Flask will take the values you put into the812session object and serialize them into a cookie. If you are finding some813values do not persist across requests, cookies are indeed enabled, and you are814not getting a clear error message, check the size of the cookie in your page815responses compared to the size supported by web browsers.816817818Message Flashing819----------------820821Good applications and user interfaces are all about feedback. If the user822does not get enough feedback they will probably end up hating the823application. Flask provides a really simple way to give feedback to a824user with the flashing system. The flashing system basically makes it825possible to record a message at the end of a request and access it on the next826(and only the next) request. This is usually combined with a layout827template to expose the message.828829To flash a message use the :func:`~flask.flash` method, to get hold of the830messages you can use :func:`~flask.get_flashed_messages` which is also831available in the templates. Check out the :ref:`message-flashing-pattern`832for a full example.833834Logging835-------836837.. versionadded:: 0.3838839Sometimes you might be in a situation where you deal with data that840should be correct, but actually is not. For example you may have some client-side841code that sends an HTTP request to the server but it's obviously842malformed. This might be caused by a user tampering with the data, or the843client code failing. Most of the time it's okay to reply with ``400 Bad844Request`` in that situation, but sometimes that won't do and the code has845to continue working.846847You may still want to log that something fishy happened. This is where848loggers come in handy. As of Flask 0.3 a logger is preconfigured for you849to use.850851Here are some example log calls::852853 app.logger.debug('A value for debugging')854 app.logger.warning('A warning occurred (%d apples)', 42)855 app.logger.error('An error occurred')856857The attached :attr:`~flask.Flask.logger` is a standard logging858:class:`~logging.Logger`, so head over to the official `logging859documentation <https://docs.python.org/library/logging.html>`_ for more860information.861862Hooking in WSGI Middlewares863---------------------------864865If you want to add a WSGI middleware to your application you can wrap the866internal WSGI application. For example if you want to use one of the867middlewares from the Werkzeug package to work around bugs in lighttpd, you868can do it like this::869870 from werkzeug.contrib.fixers import LighttpdCGIRootFix871 app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)872873.. _quickstart_deployment:874875Deploying to a Web Server876-------------------------877878Ready to deploy your new Flask app? To wrap up the quickstart, you can879immediately deploy to a hosted platform, all of which offer a free plan for880small projects:881882- `Deploying Flask on Heroku <https://devcenter.heroku.com/articles/getting-started-with-python>`_883- `Deploying WSGI on dotCloud <http://docs.dotcloud.com/services/python/>`_884 with `Flask-specific notes <http://flask.pocoo.org/snippets/48/>`_885886Other places where you can host your Flask app:887888- `Deploying Flask on Webfaction <http://flask.pocoo.org/snippets/65/>`_889- `Deploying Flask on Google App Engine <https://github.com/kamalgill/flask-appengine-template>`_890- `Sharing your Localhost Server with Localtunnel <http://flask.pocoo.org/snippets/89/>`_891892If you manage your own hosts and would like to host yourself, see the chapter893on :ref:`deployment`.