quickstart.rst
This file
Path
docs/quickstart.rst
824 lines · 29.8 KiB
Last changed by
Updated the documentation to show how to set cookies for not yet existing responsesArmin Ronacherbefore adoptionb40af3c
History of this fileTake it
The walk stopped after 200 commits: lines older than b36d7b3 point at it.
Added class based view documentationArmin Ronacherbefore adoptionb36d7b3
lines 1–20why, one step back1.. _quickstart:23Quickstart4==========56Eager to get started? This page gives a good introduction in how to get7started with Flask. This assumes you already have Flask installed. If8you do not, head over to the :ref:`installation` section.91011A Minimal Application12---------------------1314A minimal Flask application looks something like this::1516 from flask import Flask17 app = Flask(__name__)1819 @app.route('/')20 def hello_world():Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086
line 21why, one step back21 return 'Hello World!'Added class based view documentationArmin Ronacherbefore adoptionb36d7b3
lines 22–128why, one step back2223 if __name__ == '__main__':24 app.run()2526Just save it as `hello.py` or something similar and run it with your27Python interpreter. Make sure to not call your application `flask.py`28because this would conflict with Flask itself.2930::3132 $ python hello.py33 * Running on http://127.0.0.1:5000/3435Head over to `http://127.0.0.1:5000/ <http://127.0.0.1:5000/>`_, you should36see your hello world greeting.3738So what did that code do?39401. First we imported the :class:`~flask.Flask` class. An instance of this41 class will be our WSGI application. The first argument is the name of42 the application's module. If you are using a single module (like here)43 you should use `__name__` because depending on if it's started as44 application or imported as module the name will be different45 (``'__main__'`` versus the actual import name). For more information46 on that, have a look at the :class:`~flask.Flask` documentation.472. Next we create an instance of it. We pass it the name of the module /48 package. This is needed so that Flask knows where it should look for49 templates, static files and so on.503. Then we use the :meth:`~flask.Flask.route` decorator to tell Flask51 what URL should trigger our function.524. The function then has a name which is also used to generate URLs to53 that particular function, and returns the message we want to display in54 the user's browser.555. Finally we use the :meth:`~flask.Flask.run` function to run the56 local server with our application. The ``if __name__ == '__main__':``57 makes sure the server only runs if the script is executed directly from58 the Python interpreter and not used as imported module.5960To stop the server, hit control-C.6162.. _public-server:6364.. admonition:: Externally Visible Server6566 If you run the server you will notice that the server is only available67 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. If you have `debug` disabled70 or trust the users on your network, you can make the server publicly71 available.7273 Just change the call of the :meth:`~flask.Flask.run` method to look74 like this::7576 app.run(host='0.0.0.0')7778 This tells your operating system to listen on a public IP.798081Debug Mode82----------8384The :meth:`~flask.Flask.run` method is nice to start a local85development server, but you would have to restart it manually after each86change you do to code. That is not very nice and Flask can do better. If87you enable the debug support the server will reload itself on code changes88and 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 to run::9798 app.run(debug=True)99100Both will have exactly the 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. That makes it a major security107 risk 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 action115116.. admonition:: Working With Other Debuggers117118 Debuggers interfere with each other. If you are using another debugger119 (e.g. PyDev or IntelliJ), you may need to set ``app.debug = False``.120121122Routing123-------124125Modern web applications have beautiful URLs. This helps people remember126the URLs which is especially handy for applications that are used from127mobile devices with slower network connections. If the user can directly128go to the desired page without having to hit the index page it is moreLess annoying gender neutral formsArmin Ronacherbefore adoption22d468e
line 129why, one step back129likely they will like the page and come back next time.Added class based view documentationArmin Ronacherbefore adoptionb36d7b3
lines 130–590why, one step back130131As you have seen above, the :meth:`~flask.Flask.route` decorator is used132to bind a function to a URL. Here are some basic examples::133134 @app.route('/')135 def index():136 return 'Index Page'137138 @app.route('/hello')139 def hello():140 return 'Hello World'141142But there is more to it! You can make certain parts of the URL dynamic143and attach multiple rules to a function.144145Variable Rules146``````````````147148To add variable parts to a URL you can mark these special sections as149``<variable_name>``. Such a part is then passed as keyword argument to150your function. Optionally a converter can be specified by specifying a151rule with ``<converter:variable_name>``. Here are some nice examples::152153 @app.route('/user/<username>')154 def show_user_profile(username):155 # show the user profile for that user156 pass157158 @app.route('/post/<int:post_id>')159 def show_post(post_id):160 # show the post with the given id, the id is an integer161 pass162163The following converters exist:164165=========== ===========================================166`int` accepts integers167`float` like `int` but for floating point values168`path` like the default but also accepts slashes169=========== ===========================================170171.. admonition:: Unique URLs / Redirection Behaviour172173 Flask's URL rules are based on Werkzeug's routing module. The idea174 behind that module is to ensure nice looking and also unique URLs based175 on behaviour Apache and earlier servers coined.176177 Take these two rules::178179 @app.route('/projects/')180 def projects():181 pass182183 @app.route('/about')184 def about():185 pass186187 They look rather similar, the difference is the trailing slash in the188 URL *definition*. In the first case, the canonical URL for the189 `projects` endpoint has a trailing slash. It's similar to a folder in190 that sense. Accessing it without a trailing slash will cause Flask to191 redirect to the canonical URL with the trailing slash.192193 However in the second case the URL is defined without a slash so it194 behaves similar to a file and accessing the URL with a trailing slash195 will be a 404 error.196197 Why is this? This allows relative URLs to continue working if users198 access the page when they forget a trailing slash. This behaviour is199 also consistent with how Apache and other servers work. Also, the URLs200 will stay unique which helps search engines not indexing the same page201 twice.202203204.. _url-building:205206URL Building207````````````208209If it can match URLs, can it also generate them? Of course it can. To210build a URL to a specific function you can use the :func:`~flask.url_for`211function. It accepts the name of the function as first argument and a212number of keyword arguments, each corresponding to the variable part of213the URL rule. Unknown variable parts are appended to the URL as query214parameter. Here are some examples:215216>>> from flask import Flask, url_for217>>> app = Flask(__name__)218>>> @app.route('/')219... def index(): pass220...221>>> @app.route('/login')222... def login(): pass223...224>>> @app.route('/user/<username>')225... def profile(username): pass226...227>>> with app.test_request_context():228... print url_for('index')229... print url_for('login')230... print url_for('login', next='/')231... print url_for('profile', username='John Doe')232...233/234/login235/login?next=/236/user/John%20Doe237238(This also uses the :meth:`~flask.Flask.test_request_context` method239explained below. It basically tells Flask to think we are handling a240request even though we are not, we are in an interactive Python shell.241Have a look at the explanation below. :ref:`context-locals`).242243Why would you want to build URLs instead of hardcoding them in your244templates? There are three good reasons for this:2452461. reversing is often more descriptive than hardcoding the URLs. Also and247 more importantly you can change URLs in one go without having to change248 the URLs all over the place.2492. URL building will handle escaping of special characters and Unicode250 data transparently for you, you don't have to deal with that.2513. If your application is placed outside the URL root (so say in252 ``/myapplication`` instead of ``/``), :func:`~flask.url_for` will253 handle that properly for you.254255256HTTP Methods257````````````258259HTTP (the protocol web applications are speaking) knows different methods260to access URLs. By default a route only answers to `GET` requests, but261that can be changed by providing the `methods` argument to the262:meth:`~flask.Flask.route` decorator. Here are some examples::263264 @app.route('/login', methods=['GET', 'POST'])265 def login():266 if request.method == 'POST':267 do_the_login()268 else:269 show_the_login_form()270271If `GET` is present, `HEAD` will be added automatically for you. You272don't have to deal with that. It will also make sure that `HEAD` requests273are handled like the `HTTP RFC`_ (the document describing the HTTP274protocol) demands, so you can completely ignore that part of the HTTP275specification. Likewise as of Flask 0.6, `OPTIONS` is implemented for you276as well automatically.277278You have no idea what an HTTP method is? Worry not, here is a quick279introduction to HTTP methods and why they matter:280281The HTTP method (also often called "the verb") tells the server what the282clients wants to *do* with the requested page. The following methods are283very common:284285`GET`286 The browser tells the server to just *get* the information stored on287 that page and send it. This is probably the most common method.288289`HEAD`290 The browser tells the server to get the information, but it is only291 interested in the *headers*, not the content of the page. An292 application is supposed to handle that as if a `GET` request was293 received but to not deliver the actual content. In Flask you don't294 have to deal with that at all, the underlying Werkzeug library handles295 that for you.296297`POST`298 The browser tells the server that it wants to *post* some new299 information to that URL and that the server must ensure the data is300 stored and only stored once. This is how HTML forms are usually301 transmitting data to the server.302303`PUT`304 Similar to `POST` but the server might trigger the store procedure305 multiple times by overwriting the old values more than once. Now you306 might be asking why is this useful, but there are some good reasons307 to do it this way. Consider that the connection gets lost during308 transmission: in this situation a system between the browser and the309 server might receive the request safely a second time without breaking310 things. With `POST` that would not be possible because it must only311 be triggered once.312313`DELETE`314 Remove the information at the given location.315316`OPTIONS`317 Provides a quick way for a client to figure out which methods are318 supported by this URL. Starting with Flask 0.6, this is implemented319 for you automatically.320321Now the interesting part is that in HTML4 and XHTML1, the only methods a322form can submit to the server are `GET` and `POST`. But with JavaScript323and future HTML standards you can use the other methods as well. Furthermore324HTTP has become quite popular lately and browsers are no longer the only325clients that are using HTTP. For instance, many revision control system326use it.327328.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt329330Static Files331------------332333Dynamic web applications need static files as well. That's usually where334the CSS and JavaScript files are coming from. Ideally your web server is335configured to serve them for you, but during development Flask can do that336as well. Just create a folder called `static` in your package or next to337your module and it will be available at `/static` on the application.338339To generate URLs to that part of the URL, use the special ``'static'`` URL340name::341342 url_for('static', filename='style.css')343344The file has to be stored on the filesystem as ``static/style.css``.345346Rendering Templates347-------------------348349Generating HTML from within Python is not fun, and actually pretty350cumbersome because you have to do the HTML escaping on your own to keep351the application secure. Because of that Flask configures the `Jinja2352<http://jinja.pocoo.org/2/>`_ template engine for you automatically.353354To render a template you can use the :func:`~flask.render_template`355method. All you have to do is to provide the name of the template and the356variables you want to pass to the template engine as keyword arguments.357Here's a simple example of how to render a template::358359 from flask import render_template360361 @app.route('/hello/')362 @app.route('/hello/<name>')363 def hello(name=None):364 return render_template('hello.html', name=name)365366Flask will look for templates in the `templates` folder. So if your367application is a module, that folder is next to that module, if it's a368package it's actually inside your package:369370**Case 1**: a module::371372 /application.py373 /templates374 /hello.html375376**Case 2**: a package::377378 /application379 /__init__.py380 /templates381 /hello.html382383For templates you can use the full power of Jinja2 templates. Head over384to the the official `Jinja2 Template Documentation385<http://jinja.pocoo.org/2/documentation/templates>`_ for more information.386387Here is an example template:388389.. sourcecode:: html+jinja390391 <!doctype html>392 <title>Hello from Flask</title>393 {% if name %}394 <h1>Hello {{ name }}!</h1>395 {% else %}396 <h1>Hello World!</h1>397 {% endif %}398399Inside templates you also have access to the :class:`~flask.request`,400:class:`~flask.session` and :class:`~flask.g` [#]_ objects401as well as the :func:`~flask.get_flashed_messages` function.402403Templates are especially useful if inheritance is used. If you want to404know how that works, head over to the :ref:`template-inheritance` pattern405documentation. Basically template inheritance makes it possible to keep406certain elements on each page (like header, navigation and footer).407408Automatic escaping is enabled, so if name contains HTML it will be escaped409automatically. If you can trust a variable and you know that it will be410safe HTML (because for example it came from a module that converts wiki411markup to HTML) you can mark it as safe by using the412:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the413template. Head over to the Jinja 2 documentation for more examples.414415Here is a basic introduction to how the :class:`~jinja2.Markup` class works:416417>>> from flask import Markup418>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'419Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')420>>> Markup.escape('<blink>hacker</blink>')421Markup(u'<blink>hacker</blink>')422>>> Markup('<em>Marked up</em> » HTML').striptags()423u'Marked up \xbb HTML'424425.. versionchanged:: 0.5426427 Autoescaping is no longer enabled for all templates. The following428 extensions for templates trigger autoescaping: ``.html``, ``.htm``,429 ``.xml``, ``.xhtml``. Templates loaded from a string will have430 autoescaping disabled.431432.. [#] Unsure what that :class:`~flask.g` object is? It's something in which433 you can store information for your own needs, check the documentation of434 that object (:class:`~flask.g`) and the :ref:`sqlite3` for more435 information.436437438Accessing Request Data439----------------------440441For web applications it's crucial to react to the data a client sent to442the server. In Flask this information is provided by the global443:class:`~flask.request` object. If you have some experience with Python444you might be wondering how that object can be global and how Flask445manages to still be threadsafe. The answer are context locals:446447448.. _context-locals:449450Context Locals451``````````````452453.. admonition:: Insider Information454455 If you want to understand how that works and how you can implement456 tests with context locals, read this section, otherwise just skip it.457458Certain objects in Flask are global objects, but not of the usual kind.459These objects are actually proxies to objects that are local to a specific460context. What a mouthful. But that is actually quite easy to understand.461462Imagine the context being the handling thread. A request comes in and the463webserver decides to spawn a new thread (or something else, the464underlying object is capable of dealing with other concurrency systems465than threads as well). When Flask starts its internal request handling it466figures out that the current thread is the active context and binds the467current application and the WSGI environments to that context (thread).468It does that in an intelligent way that one application can invoke another469application without breaking.470471So what does this mean to you? Basically you can completely ignore that472this is the case unless you are doing something like unittesting. You473will notice that code that depends on a request object will suddenly break474because there is no request object. The solution is creating a request475object yourself and binding it to the context. The easiest solution for476unittesting is by using the :meth:`~flask.Flask.test_request_context`477context manager. In combination with the `with` statement it will bind a478test request so that you can interact with it. Here is an example::479480 from flask import request481482 with app.test_request_context('/hello', method='POST'):483 # now you can do something with the request until the484 # end of the with block, such as basic assertions:485 assert request.path == '/hello'486 assert request.method == 'POST'487488The other possibility is passing a whole WSGI environment to the489:meth:`~flask.Flask.request_context` method::490491 from flask import request492493 with app.request_context(environ):494 assert request.method == 'POST'495496The Request Object497``````````````````498499The request object is documented in the API section and we will not cover500it here in detail (see :class:`~flask.request`). Here is a broad overview of501some of the most common operations. First of all you have to import it from502the `flask` module::503504 from flask import request505506The current request method is available by using the507:attr:`~flask.request.method` attribute. To access form data (data508transmitted in a `POST` or `PUT` request) you can use the509:attr:`~flask.request.form` attribute. Here is a full example of the two510attributes mentioned above::511512 @app.route('/login', methods=['POST', 'GET'])513 def login():514 error = None515 if request.method == 'POST':516 if valid_login(request.form['username'],517 request.form['password']):518 return log_the_user_in(request.form['username'])519 else:520 error = 'Invalid username/password'521 # this is executed if the request method was GET or the522 # credentials were invalid523524What happens if the key does not exist in the `form` attribute? In that525case a special :exc:`KeyError` is raised. You can catch it like a526standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request527error page is shown instead. So for many situations you don't have to528deal with that problem.529530To access parameters submitted in the URL (``?key=value``) you can use the531:attr:`~flask.request.args` attribute::532533 searchword = request.args.get('q', '')534535We recommend accessing URL parameters with `get` or by catching the536`KeyError` because users might change the URL and presenting them a 400537bad request page in that case is not user friendly.538539For a full list of methods and attributes of the request object, head over540to the :class:`~flask.request` documentation.541542543File Uploads544````````````545546You can handle uploaded files with Flask easily. Just make sure not to547forget to set the ``enctype="multipart/form-data"`` attribute on your HTML548form, otherwise the browser will not transmit your files at all.549550Uploaded files are stored in memory or at a temporary location on the551filesystem. You can access those files by looking at the552:attr:`~flask.request.files` attribute on the request object. Each553uploaded file is stored in that dictionary. It behaves just like a554standard Python :class:`file` object, but it also has a555:meth:`~werkzeug.datastructures.FileStorage.save` method that allows you to store that556file on the filesystem of the server. Here is a simple example showing how557that works::558559 from flask import request560561 @app.route('/upload', methods=['GET', 'POST'])562 def upload_file():563 if request.method == 'POST':564 f = request.files['the_file']565 f.save('/var/www/uploads/uploaded_file.txt')566 ...567568If you want to know how the file was named on the client before it was569uploaded to your application, you can access the570:attr:`~werkzeug.datastructures.FileStorage.filename` attribute. However please keep in571mind that this value can be forged so never ever trust that value. If you572want to use the filename of the client to store the file on the server,573pass it through the :func:`~werkzeug.utils.secure_filename` function that574Werkzeug provides for you::575576 from flask import request577 from werkzeug import secure_filename578579 @app.route('/upload', methods=['GET', 'POST'])580 def upload_file():581 if request.method == 'POST':582 f = request.files['the_file']583 f.save('/var/www/uploads/' + secure_filename(f.filename))584 ...585586For some better examples, checkout the :ref:`uploading-files` pattern.587588Cookies589```````590Improved cookie documentationArmin Ronacherbefore adoption13005d7
lines 591–622why, one step back591To access cookies you can use the :attr:`~flask.Request.cookies`592attribute. To set cookies you can use the593:attr:`~flask.Response.set_cookie` method of response objects. The594:attr:`~flask.Request.cookies` attribute of request objects is a595dictionary with all the cookies the client transmits. If you want to use596sessions, do not use the cookies directly but instead use the597:ref:`sessions` in Flask that add some security on top of cookies for you.598599Reading cookies::600601 from flask import request602603 @app.route('/')604 def index():605 username = request.cookies.get('username')606 # use cookies.get(key) instead of cookies[key] to not get a607 # KeyError if the cookie is missing.608609Storing cookies::610611 from flask import make_response612613 @app.route('/')614 def index():615 resp = make_response(render_template(...))616 resp.set_cookie('username', 'the username')617 return resp618619Note that cookies are set on response objects. Since you normally you620just return strings from the view functions Flask will convert them into621response objects for you. If you explicitly want to do that you can use622the :meth:`~flask.make_response` function and then modify it.Added class based view documentationArmin Ronacherbefore adoptionb36d7b3
line 623why, one step back623Updated the documentation to show how to set cookies for not yet existing responsesArmin Ronacherbefore adoptionb40af3c
lines 624–627why, one step back624Sometimes you might want to set a cookie at a point where the response625object does not exist yet. This is possible by utilizing the626:ref:`deferred-callbacks` pattern.627Extended quickstart docs for the headersArmin Ronacherbefore adoption5b16532
line 628why, one step back628For this also see :ref:`about-responses`.Added class based view documentationArmin Ronacherbefore adoptionb36d7b3
lines 629–648why, one step back629630Redirects and Errors631--------------------632633To redirect a user to somewhere else you can use the634:func:`~flask.redirect` function. To abort a request early with an error635code use the :func:`~flask.abort` function. Here an example how this works::636637 from flask import abort, redirect, url_for638639 @app.route('/')640 def index():641 return redirect(url_for('login'))642643 @app.route('/login')644 def login():645 abort(401)646 this_is_never_executed()647648This is a rather pointless example because a user will be redirected fromLess annoying gender neutral formsArmin Ronacherbefore adoption22d468e
line 649why, one step back649the index to a page they cannot access (401 means access denied) but itAdded class based view documentationArmin Ronacherbefore adoptionb36d7b3
lines 650–664why, one step back650shows how that works.651652By default a black and white error page is shown for each error code. If653you want to customize the error page, you can use the654:meth:`~flask.Flask.errorhandler` decorator::655656 from flask import render_template657658 @app.errorhandler(404)659 def page_not_found(error):660 return render_template('page_not_found.html'), 404661662Note the ``404`` after the :func:`~flask.render_template` call. This663tells Flask that the status code of that page should be 404 which means664not found. By default 200 is assumed which translates to: all went well.Extended quickstart docs for the headersArmin Ronacherbefore adoption5b16532
lines 665–707why, one step back665666.. _about-responses:667668About Responses669---------------670671The return value from a view function is automatically converted into a672response object for you. If the return value is a string it's converted673into a response object with the string as response body, an ``200 OK``674error code and a ``text/html`` mimetype. The logic that Flask applies to675converting return values into response objects is as follows:6766771. If a response object of the correct type is returned it's directly678 returned from the view.6792. If it's a string, a response object is created with that data and the680 default parameters.6813. If a tuple is returned the response object is created by passing the682 tuple as arguments to the response object's constructor.6834. If neither of that works, Flask will assume the return value is a684 valid WSGI application and converts that into a response object.685686If you want to get hold of the resulting response object inside the view687you can use the :func:`~flask.make_response` function.688689Imagine you have a view like this:690691.. sourcecode:: python692693 @app.errorhandler(404)694 def not_found(error):695 return render_template('error.html'), 404696697You just need to wrap the return expression with698:func:`~flask.make_response` and get the result object to modify it, then699return it:700701.. sourcecode:: python702703 @app.errorhandler(404)704 def not_found(error):705 resp = make_response(render_template('error.html'), 404)706 resp.headers['X-Something'] = 'A value'707 return respAdded class based view documentationArmin Ronacherbefore adoptionb36d7b3
lines 708–718why, one step back708709.. _sessions:710711Sessions712--------713714Besides the request object there is also a second object called715:class:`~flask.session` that allows you to store information specific to a716user from one request to the next. This is implemented on top of cookies717for you and signs the cookies cryptographically. What this means is that718the user could look at the contents of your cookie but not modify it,Less annoying gender neutral formsArmin Ronacherbefore adoption22d468e
line 719why, one step back719unless they know the secret key used for signing.Added class based view documentationArmin Ronacherbefore adoptionb36d7b3
lines 720–774why, one step back720721In order to use sessions you have to set a secret key. Here is how722sessions work::723724 from flask import Flask, session, redirect, url_for, escape, request725726 app = Flask(__name__)727728 @app.route('/')729 def index():730 if 'username' in session:731 return 'Logged in as %s' % escape(session['username'])732 return 'You are not logged in'733734 @app.route('/login', methods=['GET', 'POST'])735 def login():736 if request.method == 'POST':737 session['username'] = request.form['username']738 return redirect(url_for('index'))739 return '''740 <form action="" method="post">741 <p><input type=text name=username>742 <p><input type=submit value=Login>743 </form>744 '''745746 @app.route('/logout')747 def logout():748 # remove the username from the session if its there749 session.pop('username', None)750 return redirect(url_for('index'))751752 # set the secret key. keep this really secret:753 app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'754755The here mentioned :func:`~flask.escape` does escaping for you if you are756not using the template engine (like in this example).757758.. admonition:: How to generate good secret keys759760 The problem with random is that it's hard to judge what random is. And761 a secret key should be as random as possible. Your operating system762 has ways to generate pretty random stuff based on a cryptographic763 random generator which can be used to get such a key:764765 >>> import os766 >>> os.urandom(24)767 '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'768769 Just take that thing and copy/paste it into your code and you're done.770771Message Flashing772----------------773774Good applications and user interfaces are all about feedback. If the userLess annoying gender neutral formsArmin Ronacherbefore adoption22d468e
line 775why, one step back775does not get enough feedback they will probably end up hating theAdded class based view documentationArmin Ronacherbefore adoptionb36d7b3
lines 776–824why, one step back776application. Flask provides a really simple way to give feedback to a777user with the flashing system. The flashing system basically makes it778possible to record a message at the end of a request and access it next779request and only next request. This is usually combined with a layout780template that does this.781782To flash a message use the :func:`~flask.flash` method, to get hold of the783messages you can use :func:`~flask.get_flashed_messages` which is also784available in the templates. Check out the :ref:`message-flashing-pattern`785for a full example.786787Logging788-------789790.. versionadded:: 0.3791792Sometimes you might be in a situation where you deal with data that793should be correct, but actually is not. For example you may have some client794side code that sends an HTTP request to the server but it's obviously795malformed. This might be caused by a user tempering with the data, or the796client code failing. Most of the time, it's okay to reply with ``400 Bad797Request`` in that situation, but sometimes that won't do and the code has798to continue working.799800You may still want to log that something fishy happened. This is where801loggers come in handy. As of Flask 0.3 a logger is preconfigured for you802to use.803804Here are some example log calls::805806 app.logger.debug('A value for debugging')807 app.logger.warning('A warning occurred (%d apples)', 42)808 app.logger.error('An error occurred')809810The attached :attr:`~flask.Flask.logger` is a standard logging811:class:`~logging.Logger`, so head over to the official `logging812documentation <http://docs.python.org/library/logging.html>`_ for more813information.814815Hooking in WSGI Middlewares816---------------------------817818If you want to add a WSGI middleware to your application you can wrap the819internal WSGI application. For example if you want to use one of the820middlewares from the Werkzeug package to work around bugs in lighttpd, you821can do it like this::822823 from werkzeug.contrib.fixers import LighttpdCGIRootFix824 app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)