quickstart.rst
This file
Path
docs/quickstart.rst
745 lines · 27.0 KiB
Last changed by
Fix some typos in the docsjgraemebefore adoptionff2786d
History of this fileTake it
The walk stopped after 200 commits: lines older than e7a9df7 point at it.
Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 1–5why, one step back1.. _quickstart:23Quickstart4==========5Proofread docs/quickstartAku Kotkavuobefore adoption43ae651
line 6why, one step back6Eager to get started? This page gives a good introduction in how to getTypo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 7–39why, one step back7started 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 that::1516 from flask import Flask17 app = Flask(__name__)1819 @app.route('/')20 def hello_world():21 return "Hello World!"2223 if __name__ == '__main__':24 app.run()2526Just save it as `hello.py` or something similar and run it with your27Python interpreter. Make sure to not call your application `flask.py`28because this would conflict with Flask itself.2930::3132 $ python hello.py33 * Running on http://127.0.0.1:5000/3435Head over to `http://127.0.0.1:5000/ <http://127.0.0.1:5000/>`_, you should36see your hello world greeting.3738So what did that code do?39Proofread docs/quickstartAku Kotkavuobefore adoption43ae651
line 40why, one step back401. First we imported the :class:`~flask.Flask` class. An instance of thisExplained Flask constructor better. This fixes #70Armin Ronacherbefore adoption3ab318a
lines 41–46why, one step back41 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.Proofread docs/quickstartAku Kotkavuobefore adoption43ae651
line 47why, one step back472. Next we create an instance of it. We pass it the name of the module /Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 48–83why, one step back48 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----------83Proofread docs/quickstartAku Kotkavuobefore adoption43ae651
line 84why, one step back84The :meth:`~flask.Flask.run` method is nice to start a localTypo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 85–103why, one step back85development 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:: Attention103Proofread docs/quickstartAku Kotkavuobefore adoption43ae651
lines 104–107why, one step back104 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**.Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 108–119why, one step back108109Screenshot of the debugger in action:110111.. image:: _static/debugger.png112 :align: center113 :class: screenshot114 :alt: screenshot of debugger in action115116117Routing118-------119Proofread docs/quickstartAku Kotkavuobefore adoption43ae651
lines 120–125why, one step back120Modern web applications have beautiful URLs. This helps people remember121the URLs which is especially handy for applications that are used from122mobile devices with slower network connections. If the user can directly123go to the desired page without having to hit the index page it is more124likely he will like the page and come back next time.125Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
line 126why, one step back126As you have seen above, the :meth:`~flask.Flask.route` decorator is usedProofread docs/quickstartAku Kotkavuobefore adoption43ae651
line 127why, one step back127to bind a function to a URL. Here are some basic examples::Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 128–136why, one step back128129 @app.route('/')130 def index():131 return 'Index Page'132133 @app.route('/hello')134 def hello():135 return 'Hello World'136Proofread docs/quickstartAku Kotkavuobefore adoption43ae651
lines 137–138why, one step back137But there is more to it! You can make certain parts of the URL dynamic138and attach multiple rules to a function.Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 139–145why, one step back139140Variable Rules141``````````````142143To add variable parts to a URL you can mark these special sections as144``<variable_name>``. Such a part is then passed as keyword argument to145your function. Optionally a converter can be specified by specifying aProofread docs/quickstartAku Kotkavuobefore adoption43ae651
line 146why, one step back146rule with ``<converter:variable_name>``. Here are some nice examples::Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 147–203why, one step back147148 @app.route('/user/<username>')149 def show_user_profile(username):150 # show the user profile for that user151 pass152153 @app.route('/post/<int:post_id>')154 def show_post(post_id):155 # show the post with the given id, the id is an integer156 pass157158The following converters exist:159160=========== ===========================================161`int` accepts integers162`float` like `int` but for floating point values163`path` like the default but also accepts slashes164=========== ===========================================165166.. admonition:: Unique URLs / Redirection Behaviour167168 Flask's URL rules are based on Werkzeug's routing module. The idea169 behind that module is to ensure nice looking and also unique URLs based170 on behaviour Apache and earlier servers coined.171172 Take these two rules::173174 @app.route('/projects/')175 def projects():176 pass177178 @app.route('/about')179 def about():180 pass181182 They look rather similar, the difference is the trailing slash in the183 URL *definition*. In the first case, the canonical URL for the184 `projects` endpoint has a trailing slash. It's similar to a folder in185 that sense. Accessing it without a trailing slash will cause Flask to186 redirect to the canonical URL with the trailing slash.187188 However in the second case the URL is defined without a slash so it189 behaves similar to a file and accessing the URL with a trailing slash190 will be a 404 error.191192 Why is this? This allows relative URLs to continue working if users193 access the page when they forget a trailing slash. This behaviour is194 also consistent with how Apache and other servers work. Also, the URLs195 will stay unique which helps search engines not indexing the same page196 twice.197198199.. _url-building:200201URL Building202````````````203Proofread docs/quickstartAku Kotkavuobefore adoption43ae651
line 204why, one step back204If it can match URLs, can it also generate them? Of course it can. ToTypo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 205–208why, one step back205build a URL to a specific function you can use the :func:`~flask.url_for`206function. It accepts the name of the function as first argument and a207number of keyword arguments, each corresponding to the variable part of208the URL rule. Unknown variable parts are appended to the URL as queryProofread docs/quickstartAku Kotkavuobefore adoption43ae651
line 209why, one step back209parameter. Here are some examples:Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 210–233why, one step back210211>>> from flask import Flask, url_for212>>> app = Flask(__name__)213>>> @app.route('/')214... def index(): pass215...216>>> @app.route('/login')217... def login(): pass218...219>>> @app.route('/user/<username>')220... def profile(username): pass221...222>>> with app.test_request_context():223... print url_for('index')224... print url_for('login')225... print url_for('login', next='/')226... print url_for('profile', username='John Doe')227...228/229/login230/login?next=/231/user/John%20Doe232233(This also uses the :meth:`~flask.Flask.test_request_context` methodFix some typos in the docsjgraemebefore adoptionff2786d
line 234why, one step back234explained below. It basically tells Flask to think we are handling aTypo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 235–256why, one step back235request even though we are not, we are in an interactive Python shell.236Have a look at the explanation below. :ref:`context-locals`).237238Why would you want to build URLs instead of hardcoding them in your239templates? There are three good reasons for this:2402411. reversing is often more descriptive than hardcoding the URLs. Also and242 more importantly you can change URLs in one go without having to change243 the URLs all over the place.2442. URL building will handle escaping of special characters and Unicode245 data transparently for you, you don't have to deal with that.2463. If your application is placed outside the URL root (so say in247 ``/myapplication`` instead of ``/``), :func:`~flask.url_for` will248 handle that properly for you.249250251HTTP Methods252````````````253254HTTP (the protocol web applications are speaking) knows different methods255to access URLs. By default a route only answers to `GET` requests, but256that can be changed by providing the `methods` argument to theProofread docs/quickstartAku Kotkavuobefore adoption43ae651
line 257why, one step back257:meth:`~flask.Flask.route` decorator. Here are some examples::Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 258–269why, one step back258259 @app.route('/login', methods=['GET', 'POST'])260 def login():261 if request.method == 'POST':262 do_the_login()263 else:264 show_the_login_form()265266If `GET` is present, `HEAD` will be added automatically for you. You267don't have to deal with that. It will also make sure that `HEAD` requests268are handled like the `HTTP RFC`_ (the document describing the HTTP269protocol) demands, so you can completely ignore that part of the HTTPAdded support for automagic OPTIONSArmin Ronacherbefore adoption5e1b103
lines 270–271why, one step back270specification. Likewise as of Flask 0.6, `OPTIONS` is implemented for you271as well automatically.Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
line 272why, one step back272Proofread docs/quickstartAku Kotkavuobefore adoption43ae651
lines 273–274why, one step back273You have no idea what an HTTP method is? Worry not, here is a quick274introduction to HTTP methods and why they matter:Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 275–280why, one step back275276The HTTP method (also often called "the verb") tells the server what the277clients wants to *do* with the requested page. The following methods are278very common:279280`GET`Proofread docs/quickstartAku Kotkavuobefore adoption43ae651
lines 281–282why, one step back281 The browser tells the server to just *get* the information stored on282 that page and send it. This is probably the most common method.Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 283–284why, one step back283284`HEAD`Proofread docs/quickstartAku Kotkavuobefore adoption43ae651
line 285why, one step back285 The browser tells the server to get the information, but it is onlyTypo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 286–287why, one step back286 interested in the *headers*, not the content of the page. An287 application is supposed to handle that as if a `GET` request wasProofread docs/quickstartAku Kotkavuobefore adoption43ae651
lines 288–290why, one step back288 received but to not deliver the actual content. In Flask you don't289 have to deal with that at all, the underlying Werkzeug library handles290 that for you.Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 291–300why, one step back291292`POST`293 The browser tells the server that it wants to *post* some new294 information to that URL and that the server must ensure the data is295 stored and only stored once. This is how HTML forms are usually296 transmitting data to the server.297298`PUT`299 Similar to `POST` but the server might trigger the store procedure300 multiple times by overwriting the old values more than once. Now youProofread docs/quickstartAku Kotkavuobefore adoption43ae651
lines 301–304why, one step back301 might be asking why is this useful, but there are some good reasons302 to do it this way. Consider that the connection gets lost during303 transmission: in this situation a system between the browser and the304 server might receive the request safely a second time without breakingTypo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 305–308why, one step back305 things. With `POST` that would not be possible because it must only306 be triggered once.307308`DELETE`Proofread docs/quickstartAku Kotkavuobefore adoption43ae651
line 309why, one step back309 Remove the information at the given location.Added support for automagic OPTIONSArmin Ronacherbefore adoption5e1b103
lines 310–311why, one step back310311`OPTIONS`Proofread docs/quickstartAku Kotkavuobefore adoption43ae651
lines 312–314why, one step back312 Provides a quick way for a client to figure out which methods are313 supported by this URL. Starting with Flask 0.6, this is implemented314 for you automatically.Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 315–316why, one step back315316Now the interesting part is that in HTML4 and XHTML1, the only methods aProofread docs/quickstartAku Kotkavuobefore adoption43ae651
lines 317–321why, one step back317form can submit to the server are `GET` and `POST`. But with JavaScript318and future HTML standards you can use the other methods as well. Furthermore319HTTP has become quite popular lately and browsers are no longer the only320clients that are using HTTP. For instance, many revision control system321use it.Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 322–378why, one step back322323.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt324325Static Files326------------327328Dynamic web applications need static files as well. That's usually where329the CSS and JavaScript files are coming from. Ideally your web server is330configured to serve them for you, but during development Flask can do that331as well. Just create a folder called `static` in your package or next to332your module and it will be available at `/static` on the application.333334To generate URLs to that part of the URL, use the special ``'static'`` URL335name::336337 url_for('static', filename='style.css')338339The file has to be stored on the filesystem as ``static/style.css``.340341Rendering Templates342-------------------343344Generating HTML from within Python is not fun, and actually pretty345cumbersome because you have to do the HTML escaping on your own to keep346the application secure. Because of that Flask configures the `Jinja2347<http://jinja.pocoo.org/2/>`_ template engine for you automatically.348349To render a template you can use the :func:`~flask.render_template`350method. All you have to do is to provide the name of the template and the351variables you want to pass to the template engine as keyword arguments.352Here's a simple example of how to render a template::353354 from flask import render_template355356 @app.route('/hello/')357 @app.route('/hello/<name>')358 def hello(name=None):359 return render_template('hello.html', name=name)360361Flask will look for templates in the `templates` folder. So if your362application is a module, that folder is next to that module, if it's a363package it's actually inside your package:364365**Case 1**: a module::366367 /application.py368 /templates369 /hello.html370371**Case 2**: a package::372373 /application374 /__init__.py375 /templates376 /hello.html377378For templates you can use the full power of Jinja2 templates. Head overAdded templating docs. This basically fixes #92Armin Ronacherbefore adoption4a2d2ba
lines 379–380why, one step back379to the :ref:`templating` section of the documentation or the official380`Jinja2 Template DocumentationTypo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 381–382why, one step back381<http://jinja.pocoo.org/2/documentation/templates>`_ for more information.382Proofread docs/quickstartAku Kotkavuobefore adoption43ae651
line 383why, one step back383Here is an example template:Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 384–410why, one step back384385.. sourcecode:: html+jinja386387 <!doctype html>388 <title>Hello from Flask</title>389 {% if name %}390 <h1>Hello {{ name }}!</h1>391 {% else %}392 <h1>Hello World!</h1>393 {% endif %}394395Inside templates you also have access to the :class:`~flask.request`,396:class:`~flask.session` and :class:`~flask.g` [#]_ objects397as well as the :func:`~flask.get_flashed_messages` function.398399Templates are especially useful if inheritance is used. If you want to400know how that works, head over to the :ref:`template-inheritance` pattern401documentation. Basically template inheritance makes it possible to keep402certain elements on each page (like header, navigation and footer).403404Automatic escaping is enabled, so if name contains HTML it will be escaped405automatically. If you can trust a variable and you know that it will be406safe HTML (because for example it came from a module that converts wiki407markup to HTML) you can mark it as safe by using the408:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the409template. Head over to the Jinja 2 documentation for more examples.410Proofread docs/quickstartAku Kotkavuobefore adoption43ae651
line 411why, one step back411Here is a basic introduction to how the :class:`~jinja2.Markup` class works:Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 412–420why, one step back412413>>> from flask import Markup414>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'415Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')416>>> Markup.escape('<blink>hacker</blink>')417Markup(u'<blink>hacker</blink>')418>>> Markup('<em>Marked up</em> » HTML').striptags()419u'Marked up \xbb HTML'420Started working on refactoring Jinja integrationArmin Ronacherbefore adoption7599046
lines 421–424why, one step back421.. versionchanged:: 0.5422423 Autoescaping is no longer enabled for all templates. The following424 extensions for templates trigger autoescaping: ``.html``, ``.htm``,Proofread docs/quickstartAku Kotkavuobefore adoption43ae651
line 425why, one step back425 ``.xml``, ``.xhtml``. Templates loaded from a string will haveStarted working on refactoring Jinja integrationArmin Ronacherbefore adoption7599046
lines 426–427why, one step back426 autoescaping disabled.427Proofread docs/quickstartAku Kotkavuobefore adoption43ae651
lines 428–430why, one step back428.. [#] Unsure what that :class:`~flask.g` object is? It's something in which429 you can store information for your own needs, check the documentation of430 that object (:class:`~flask.g`) and the :ref:`sqlite3` for moreTypo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 431–453why, one step back431 information.432433434Accessing Request Data435----------------------436437For web applications it's crucial to react to the data a client sent to438the server. In Flask this information is provided by the global439:class:`~flask.request` object. If you have some experience with Python440you might be wondering how that object can be global and how Flask441manages to still be threadsafe. The answer are context locals:442443444.. _context-locals:445446Context Locals447``````````````448449.. admonition:: Insider Information450451 If you want to understand how that works and how you can implement452 tests with context locals, read this section, otherwise just skip it.453Proofread docs/quickstartAku Kotkavuobefore adoption43ae651
lines 454–456why, one step back454Certain objects in Flask are global objects, but not of the usual kind.455These objects are actually proxies to objects that are local to a specific456context. What a mouthful. But that is actually quite easy to understand.Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 457–467why, one step back457458Imagine the context being the handling thread. A request comes in and the459webserver decides to spawn a new thread (or something else, the460underlying object is capable of dealing with other concurrency systems461than threads as well). When Flask starts its internal request handling it462figures out that the current thread is the active context and binds the463current application and the WSGI environments to that context (thread).464It does that in an intelligent way that one application can invoke another465application without breaking.466467So what does this mean to you? Basically you can completely ignore thatProofread docs/quickstartAku Kotkavuobefore adoption43ae651
line 468why, one step back468this is the case unless you are doing something like unittesting. YouTypo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 469–473why, one step back469will notice that code that depends on a request object will suddenly break470because there is no request object. The solution is creating a request471object yourself and binding it to the context. The easiest solution for472unittesting is by using the :meth:`~flask.Flask.test_request_context`473context manager. In combination with the `with` statement it will bind aProofread docs/quickstartAku Kotkavuobefore adoption43ae651
line 474why, one step back474test request so that you can interact with it. Here is an example::Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 475–495why, one step back475476 from flask import request477478 with app.test_request_context('/hello', method='POST'):479 # now you can do something with the request until the480 # end of the with block, such as basic assertions:481 assert request.path == '/hello'482 assert request.method == 'POST'483484The other possibility is passing a whole WSGI environment to the485:meth:`~flask.Flask.request_context` method::486487 from flask import request488489 with app.request_context(environ):490 assert request.method == 'POST'491492The Request Object493``````````````````494495The request object is documented in the API section and we will not coverProofread docs/quickstartAku Kotkavuobefore adoption43ae651
lines 496–497why, one step back496it here in detail (see :class:`~flask.request`). Here is a broad overview of497some of the most common operations. First of all you have to import it fromTypo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 498–504why, one step back498the `flask` module::499500 from flask import request501502The current request method is available by using the503:attr:`~flask.request.method` attribute. To access form data (data504transmitted in a `POST` or `PUT` request) you can use theProofread docs/quickstartAku Kotkavuobefore adoption43ae651
line 505why, one step back505:attr:`~flask.request.form` attribute. Here is a full example of the twoTypo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 506–532why, one step back506attributes mentioned above::507508 @app.route('/login', methods=['POST', 'GET'])509 def login():510 error = None511 if request.method == 'POST':512 if valid_login(request.form['username'],513 request.form['password']):514 return log_the_user_in(request.form['username'])515 else:516 error = 'Invalid username/password'517 # this is executed if the request method was GET or the518 # credentials were invalid519520What happens if the key does not exist in the `form` attribute? In that521case a special :exc:`KeyError` is raised. You can catch it like a522standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request523error page is shown instead. So for many situations you don't have to524deal with that problem.525526To access parameters submitted in the URL (``?key=value``) you can use the527:attr:`~flask.request.args` attribute::528529 searchword = request.args.get('q', '')530531We recommend accessing URL parameters with `get` or by catching the532`KeyError` because users might change the URL and presenting them a 400Proofread docs/quickstartAku Kotkavuobefore adoption43ae651
line 533why, one step back533bad request page in that case is not user friendly.Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
line 534why, one step back534Proofread docs/quickstartAku Kotkavuobefore adoption43ae651
lines 535–536why, one step back535For a full list of methods and attributes of the request object, head over536to the :class:`~flask.request` documentation.Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 537–541why, one step back537538539File Uploads540````````````541Proofread docs/quickstartAku Kotkavuobefore adoption43ae651
lines 542–544why, one step back542You can handle uploaded files with Flask easily. Just make sure not to543forget to set the ``enctype="multipart/form-data"`` attribute on your HTML544form, otherwise the browser will not transmit your files at all.Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 545–551why, one step back545546Uploaded files are stored in memory or at a temporary location on the547filesystem. You can access those files by looking at the548:attr:`~flask.request.files` attribute on the request object. Each549uploaded file is stored in that dictionary. It behaves just like a550standard Python :class:`file` object, but it also has a551:meth:`~werkzeug.FileStorage.save` method that allows you to store thatProofread docs/quickstartAku Kotkavuobefore adoption43ae651
lines 552–553why, one step back552file on the filesystem of the server. Here is a simple example showing how553that works::Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 554–577why, one step back554555 from flask import request556557 @app.route('/upload', methods=['GET', 'POST'])558 def upload_file():559 if request.method == 'POST':560 f = request.files['the_file']561 f.save('/var/www/uploads/uploaded_file.txt')562 ...563564If you want to know how the file was named on the client before it was565uploaded to your application, you can access the566:attr:`~werkzeug.FileStorage.filename` attribute. However please keep in567mind that this value can be forged so never ever trust that value. If you568want to use the filename of the client to store the file on the server,569pass it through the :func:`~werkzeug.secure_filename` function that570Werkzeug provides for you::571572 from flask import request573 from werkzeug import secure_filename574575 @app.route('/upload', methods=['GET', 'POST'])576 def upload_file():577 if request.method == 'POST':Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption223d44d
line 578why, one step back578 f = request.files['the_file']Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 579–597why, one step back579 f.save('/var/www/uploads/' + secure_filename(f.filename))580 ...581582For some better examples, checkout the :ref:`uploading-files` pattern.583584Cookies585```````586587To access cookies you can use the :attr:`~flask.request.cookies`588attribute. Again this is a dictionary with all the cookies the client589transmits. If you want to use sessions, do not use the cookies directly590but instead use the :ref:`sessions` in Flask that add some security on top591of cookies for you.592593594Redirects and Errors595--------------------596597To redirect a user to somewhere else you can use theProofread docs/quickstartAku Kotkavuobefore adoption43ae651
lines 598–599why, one step back598:func:`~flask.redirect` function. To abort a request early with an error599code use the :func:`~flask.abort` function. Here an example how this works::Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 600–644why, one step back600601 from flask import abort, redirect, url_for602603 @app.route('/')604 def index():605 return redirect(url_for('login'))606607 @app.route('/login')608 def login():609 abort(401)610 this_is_never_executed()611612This is a rather pointless example because a user will be redirected from613the index to a page he cannot access (401 means access denied) but it614shows how that works.615616By default a black and white error page is shown for each error code. If617you want to customize the error page, you can use the618:meth:`~flask.Flask.errorhandler` decorator::619620 from flask import render_template621622 @app.errorhandler(404)623 def page_not_found(error):624 return render_template('page_not_found.html'), 404625626Note the ``404`` after the :func:`~flask.render_template` call. This627tells Flask that the status code of that page should be 404 which means628not found. By default 200 is assumed which translates to: all went well.629630.. _sessions:631632Sessions633--------634635Besides the request object there is also a second object called636:class:`~flask.session` that allows you to store information specific to a637user from one request to the next. This is implemented on top of cookies638for you and signs the cookies cryptographically. What this means is that639the user could look at the contents of your cookie but not modify it,640unless he knows the secret key used for signing.641642In order to use sessions you have to set a secret key. Here is how643sessions work::644Fixed a broken example in the docsArmin Ronacherbefore adoptione753222
line 645why, one step back645 from flask import Flask, session, redirect, url_for, escape, requestTypo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
line 646why, one step back646Fixed a broken example in the docsArmin Ronacherbefore adoptione753222
lines 647–648why, one step back647 app = Flask(__name__)648Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 649–670why, one step back649 @app.route('/')650 def index():651 if 'username' in session:652 return 'Logged in as %s' % escape(session['username'])653 return 'You are not logged in'654655 @app.route('/login', methods=['GET', 'POST'])656 def login():657 if request.method == 'POST':658 session['username'] = request.form['username']659 return redirect(url_for('index'))660 return '''661 <form action="" method="post">662 <p><input type=text name=username>663 <p><input type=submit value=Login>664 </form>665 '''666667 @app.route('/logout')668 def logout():669 # remove the username from the session if its there670 session.pop('username', None)Fixed a broken example in the docsArmin Ronacherbefore adoptione753222
line 671why, one step back671 return redirect(url_for('index'))Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 672–678why, one step back672673 # set the secret key. keep this really secret:674 app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'675676The here mentioned :func:`~flask.escape` does escaping for you if you are677not using the template engine (like in this example).678Proofread docs/quickstartAku Kotkavuobefore adoption43ae651
line 679why, one step back679.. admonition:: How to generate good secret keysTypo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 680–712why, one step back680681 The problem with random is that it's hard to judge what random is. And682 a secret key should be as random as possible. Your operating system683 has ways to generate pretty random stuff based on a cryptographic684 random generator which can be used to get such a key:685686 >>> import os687 >>> os.urandom(24)688 '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'689690 Just take that thing and copy/paste it into your code and you're done.691692Message Flashing693----------------694695Good applications and user interfaces are all about feedback. If the user696does not get enough feedback he will probably end up hating the697application. Flask provides a really simple way to give feedback to a698user with the flashing system. The flashing system basically makes it699possible to record a message at the end of a request and access it next700request and only next request. This is usually combined with a layout701template that does this.702703To flash a message use the :func:`~flask.flash` method, to get hold of the704messages you can use :func:`~flask.get_flashed_messages` which is also705available in the templates. Check out the :ref:`message-flashing-pattern`706for a full example.707708Logging709-------710711.. versionadded:: 0.3712Proofread docs/quickstartAku Kotkavuobefore adoption43ae651
lines 713–715why, one step back713Sometimes you might be in a situation where you deal with data that714should be correct, but actually is not. For example you may have some client715side code that sends an HTTP request to the server but it's obviouslyTypo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
line 716why, one step back716malformed. This might be caused by a user tempering with the data, or theProofread docs/quickstartAku Kotkavuobefore adoption43ae651
lines 717–719why, one step back717client code failing. Most of the time, it's okay to reply with ``400 Bad718Request`` in that situation, but sometimes that won't do and the code has719to continue working.Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
line 720why, one step back720Proofread docs/quickstartAku Kotkavuobefore adoption43ae651
lines 721–723why, one step back721You may still want to log that something fishy happened. This is where722loggers come in handy. As of Flask 0.3 a logger is preconfigured for you723to use.Typo in jQuery pattern docsDag Odenhallbefore adoptione7a9df7
lines 724–731why, one step back724725Here are some example log calls::726727 app.logger.debug('A value for debugging')728 app.logger.warning('A warning occurred (%d apples)', 42)729 app.logger.error('An error occurred')730731The attached :attr:`~flask.Flask.logger` is a standard loggingProofread docs/quickstartAku Kotkavuobefore adoption43ae651
lines 732–734why, one step back732:class:`~logging.Logger`, so head over to the official `logging733documentation <http://docs.python.org/library/logging.html>`_ for more734information.Added middlewares to quickstart. This fixes #88Armin Ronacherbefore adoptiona3a72e2
lines 735–739why, one step back735736Hooking in WSGI Middlewares737---------------------------738739If you want to add a WSGI middleware to your application you can wrap theFixed a typo in quickstartArmin Ronacherbefore adoption3ebc97a
line 740why, one step back740internal WSGI application. For example if you want to use one of theAdded middlewares to quickstart. This fixes #88Armin Ronacherbefore adoptiona3a72e2
lines 741–745why, one step back741middlewares from the Werkzeug package to work around bugs in lighttpd, you742can do it like this::743744 from werkzeug.contrib.fixers import LighttpdCGIRootFix745 app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)