quickstart.rst
This file
Path
docs/quickstart.rst
631 lines · 22.4 KiB
Last changed by
Added WTForms documentation.Armin Ronacherbefore adoptionce18d45
History of this fileTake it
And finished documentation for most parts.Armin Ronacherbefore adoption727c701
lines 1–2why, one step back1.. _quickstart:2Updated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621
lines 3–25why, one step back3Quickstart4==========56Eager to get started? This page gives a good introduction in how to gets7started 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()25Heavily improved documentationArmin Ronacherbefore adoption05f36c7
line 26why, one step back26Just save it as `hello.py` or something similar and run it with yourFixed a bug in setup.pyArmin Ronacherbefore adoption574e81f
lines 27–30why, one step back27Python interpreter. Make sure to not call your application `flask.py`28because this would conflict with Flask itself.2930::Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 31–36why, one step back3132 $ python hello.py33 * Running on http://localhost:5000/3435Head over to `http://localhost:5000/ <http://localhost:5000/>`_, you should36see your hello world greeting.Updated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621
lines 37–54why, one step back3738So what did that code do?39401. first we imported the :class:`~flask.Flask` class. An instance of this41 class will be our WSGI application.422. next we create an instance of it. We pass it the name of the module /43 package. This is needed so that Flask knows where it should look for44 templates, static files and so on.453. Then we use the :meth:`~flask.Flask.route` decorator to tell Flask46 what URL should trigger our function.474. The function then has a name which is also used to generate URLs to48 that particular function, and returns the message we want to display in49 the user's browser.505. Finally we use the :meth:`~flask.Flask.run` function to run the51 local server with our application. The ``if __name__ == '__main__':``52 makes sure the server only runs if the script is executed directly from53 the Python interpreter and not used as imported module.54further improved documentationArmin Ronacherbefore adoptiondf929c6
lines 55–56why, one step back55To stop the server, hit control-C.56First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
lines 57–69why, one step back57.. admonition:: Troubleshooting5859 The browser is unable to access the server? Sometimes this is60 unfortunately caused by broken IPv6 support in your operating system,61 browser or a combination. For example on Snow Leopard Google Chrome is62 known to exhibit this behaviour.6364 If the browser does not load up the page, you can change the `app.run`65 call to force IPv4 usage::6667 if __name__ == '__main__':68 app.run(host='127.0.0.1')69further improved documentationArmin Ronacherbefore adoptiondf929c6
lines 70–91why, one step back7071Debug Mode72----------7374Now that :meth:`~flask.Flask.run` method is nice to start a local75development server, but you would have to restart it manually after each76change you do to code. That is not very nice and Flask can do better. If77you enable the debug support the server will reload itself on code changes78and also provide you with a helpful debugger if things go wrong.7980There are two ways to enable debugging. Either set that flag on the81applciation object::8283 app.debug = True84 app.run()8586Or pass it to run::8788 app.run(debug=True)8990Both will have exactly the same effect.91Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 92–99why, one step back92.. admonition:: Attention9394 The interactive debugger however does not work in forking environments95 which makes it nearly impossible to use on production servers but the96 debugger still allows the execution of arbitrary code which makes it a97 major security risk and **must never be used on production machines**98 because of that.99Added screenshot of the debugger to Flask docs. Flask now runs from theArmin Ronacherbefore adoption40e0024
lines 100–106why, one step back100Screenshot of the debugger in action:101102.. image:: _static/debugger.png103 :align: center104 :class: screenshot105 :alt: screenshot of debugger in action106Updated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621
lines 107–157why, one step back107108Routing109-------110111As you have seen above, the :meth:`~flask.Flask.route` decorator is used112to bind a function to a URL. But there is more to it! You can make113certain parts of the URL dynamic and attach multiple rules to a function.114115Here some examples::116117 @app.route('/')118 def index():119 return 'Index Page'120121 @app.route('/hello')122 def hello():123 return 'Hello World'124125126Variable Rules127``````````````128129Modern web applications have beautiful URLs. This helps people remember130the URLs which is especially handy for applications that are used from131mobile devices with slower network connections. If the user can directly132go to the desired page without having to hit the index page it is more133likely he will like the page and come back next time.134135To add variable parts to a URL you can mark these special sections as136``<variable_name>``. Such a part is then passed as keyword argument to137your function. Optionally a converter can be specifed by specifying a138rule with ``<converter:variable_name>``. Here some nice examples::139140 @app.route('/user/<username>')141 def show_user_profile(username):142 # show the user profile for that user143 pass144145 @app.route('/post/<int:post_id>')146 def show_post(post_id):147 # show the post with the given id, the id is an integer148 pass149150The following converters exist:151152=========== ===========================================153`int` accepts integers154`float` like `int` but for floating point values155`path` like the default but also accepts slashes156=========== ===========================================157Heavily improved quickstart section.Armin Ronacherbefore adoption625eba4
lines 158–159why, one step back158URL Building159````````````Updated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621
line 160why, one step back160Heavily improved quickstart section.Armin Ronacherbefore adoption625eba4
lines 161–191why, one step back161If it can match URLs, can it also generate them? Of course you can. To162build a URL to a specific function you can use the :func:`~flask.url_for`163function. It accepts the name of the function as first argument and a164number of keyword arguments, each corresponding to the variable part of165the URL rule. Here some examples:166167>>> from flask import Flask, url_for168>>> app = Flask(__name__)169>>> @app.route('/')170... def index(): pass171... 172>>> @app.route('/login')173... def login(): pass174... 175>>> @app.route('/user/<username>')176... def profile(username): pass177... 178>>> with app.test_request_context():179... print url_for('index')180... print url_for('login')181... print url_for('profile', username='John Doe')182... 183/184/login185/user/John%20Doe186187(This also uses the :meth:`~flask.Flask.test_request_context` method188explained below. It basically tells flask to think we are handling a189request even though we are not, we are in an interactive Python shell.190Have a look at the explanation below. :ref:`context-locals`).191Described HTTP methodsArmin Ronacherbefore adoption8171da8
lines 192–193why, one step back192Why would you want to build URLs instead of hardcoding them in your193templates? There are three good reasons for this:Heavily improved quickstart section.Armin Ronacherbefore adoption625eba4
line 194why, one step back194Described HTTP methodsArmin Ronacherbefore adoption8171da8
lines 195–204why, one step back1951. reversing is often more descriptive than hardcoding the URLs. Also and196 more importantly you can change URLs in one go without having to change197 the URLs all over the place.1982. URL building will handle escaping of special characters and unicode199 data transparently for you, you don't have to deal with that.2003. If your application is placed outside the URL root (so say in201 ``/myapplication`` instead of ``/``), :func:`~flask.url_for` will202 handle that properly for you.203204Updated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621
lines 205–207why, one step back205HTTP Methods206````````````207Linked HTTPArmin Ronacherbefore adoption4e7aa9e
lines 208–211why, one step back208HTTP (the protocol web applications are speaking) knows different methods209to access URLs. By default a route only answers to `GET` requests, but210that can be changed by providing the `methods` argument to the211:meth:`~flask.Flask.route` decorator. Here some examples::Updated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621
lines 212–219why, one step back212213 @app.route('/login', methods=['GET', 'POST'])214 def login():215 if request.method == 'POST':216 do_the_login()217 else:218 show_the_login_form()219Linked HTTPArmin Ronacherbefore adoption4e7aa9e
lines 220–224why, one step back220If `GET` is present, `HEAD` will be added automatically for you. You221don't have to deal with that. It will also make sure that `HEAD` requests222are handled like the `HTTP RFC`_ (the document describing the HTTP223protocol) demands, so you can completely ignore that part of the HTTP224specification.Described HTTP methodsArmin Ronacherbefore adoption8171da8
lines 225–248why, one step back225226You have no idea what an HTTP method is? Worry not, here quick227introduction in HTTP methods and why they matter:228229The HTTP method (also often called "the verb") tells the server what the230clients wants to *do* with the requested page. The following methods are231very common:232233`GET`234 The Browser tells the server: just *get* me the information stored on235 that page and send them to me. This is probably the most common236 method.237238`HEAD`239 The Browser tells the server: get me the information, but I am only240 interested in the *headers*, not the content of the page. An241 application is supposed to handle that as if a `GET` request was242 received but not deliver the actual contents. In Flask you don't have243 to deal with that at all, the underlying Werkzeug library handles that244 for you.245246`POST`247 The browser tells the server that it wants to *post* some new248 information to that URL and that the server must ensure the data ismight -> mustArmin Ronacherbefore adoption85ca089
lines 249–250why, one step back249 stored and only stored once. This is how HTML forms are usually250 transmitting data to the server.Described HTTP methodsArmin Ronacherbefore adoption8171da8
lines 251–258why, one step back251252`PUT`253 Similar to `POST` but the server might trigger the store procedure254 multiple times by overwriting the old values more than once. Now you255 might be asking why this is any useful, but there are some good256 reasons to do that. Consider the connection is lost during257 transmission, in that situation a system between the browser and the258 server might sent the request safely a second time without breakingmight -> mustArmin Ronacherbefore adoption85ca089
line 259why, one step back259 things. With `POST` that would not be possible because it must onlyDescribed HTTP methodsArmin Ronacherbefore adoption8171da8
lines 260–270why, one step back260 be triggered once.261262`DELETE`263 Remove the information that the given location.264265Now the interesting part is that in HTML4 and XHTML1, the only methods a266form might submit to the server are `GET` and `POST`. But with JavaScript267and future HTML standards you can use other methods as well. Furthermore268HTTP became quite popular lately and there are more things than browsers269that are speaking HTTP. (Your revision control system for instance might270speak HTTP)Linked HTTPArmin Ronacherbefore adoption4e7aa9e
lines 271–272why, one step back271272.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txtUpdated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621
line 273why, one step back273And finished documentation for most parts.Armin Ronacherbefore adoption727c701
lines 274–289why, one step back274Static Files275------------276277Dynamic web applications need static files as well. That's usually where278the CSS and JavaScript files are coming from. Ideally your web server is279configured to serve them for you, but during development Flask can do that280as well. Just create a folder called `static` in your package or next to281your module and it will be available at `/static` on the application.282283To generate URLs to that part of the URL, use the special ``'static'`` URL284name::285286 url_for('static', filename='style.css')287288The file has to be stored on the filesystem as ``static/style.css``.289Heavily improved quickstart section.Armin Ronacherbefore adoption625eba4
lines 290–291why, one step back290Rendering Templates291-------------------Updated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621
line 292why, one step back292Heavily improved quickstart section.Armin Ronacherbefore adoption625eba4
lines 293–343why, one step back293Generating HTML from within Python is not fun, and actually pretty294cumbersome because you have to do the HTML escaping on your own to keep295the application secure. Because of that Flask configures the `Jinja2296<http://jinja.pocoo.org/2/>`_ template engine for you automatically.297298To render a template you can use the :func:`~flask.render_template`299method. All you have to do is to provide the name of the template and the300variables you want to pass to the template engine as keyword arguments.301Here a simple example of how to render a template::302303 from flask import render_template304305 @app.route('/hello/')306 @app.route('/hello/<name>')307 def hello(name=None):308 return render_template('hello.html', name=name)309310Flask will look for templates in the `templates` folder. So if your311application is a module, that folder is next to that module, if it's a312pacakge it's actually inside your package:313314**Case 1**: a module::315 316 /application.py317 /templates318 /hello.html319320**Case 2**: a package::321322 /application323 /__init__.py324 /templates325 /hello.html326327For templates you can use the full power of Jinja2 templates. Head over328to the `Jinja2 Template Documentation329<http://jinja.pocoo.org/2/documentation/templates>`_ for more information.330331Here an example template:332333.. sourcecode:: html+jinja334335 <!doctype html>336 <title>Hello from Flask</title>337 {% if name %}338 <h1>Hello {{ name }}!</h1>339 {% else %}340 <h1>Hello World!</h1>341 {% endif %}342343Inside templates you also have access to the :class:`~flask.request`,Added a security section to the foreword and a footnote to the gArmin Ronacherbefore adoption4671429
lines 344–345why, one step back344:class:`~flask.session` and :class:`~flask.g` [#]_ objects345as well as the :func:`~flask.get_flashed_messages` function.And finished documentation for most parts.Armin Ronacherbefore adoption727c701
lines 346–350why, one step back346347Templates are especially useful if inheritance is used. If you want to348know how that works, head over to the :ref:`template-inheritance` pattern349documentation. Basically template inheritance makes it possible to keep350certain elements on each page (like header, navigation and footer).Heavily improved quickstart section.Armin Ronacherbefore adoption625eba4
lines 351–367why, one step back351352Automatic escaping is enabled, so if name contains HTML it will be escaped353automatically. If you can trust a variable and you know that it will be354safe HTML (because for example it came from a module that converts wiki355markup to HTML) you can mark it as safe by using the356:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the357template. Head over to the Jinja 2 documentation for more examples.358359Here a basic introduction in how the :class:`~jinja2.Markup` class works:360361>>> from flask import Markup362>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'363Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')364>>> Markup.escape('<blink>hacker</blink>')365Markup(u'<blink>hacker</blink>')366>>> Markup('<em>Marked up</em> » HTML').striptags()367u'Marked up \xbb HTML'Added a security section to the foreword and a footnote to the gArmin Ronacherbefore adoption4671429
lines 368–370why, one step back368369.. [#] Unsure what that :class:`~flask.g` object is? It's something you370 can store information on yourself, check the documentation of thatAdded WTForms documentation.Armin Ronacherbefore adoptionce18d45
line 371why, one step back371 object (:class:`~flask.g`) and the :ref:`sqlite3` for moreAdded a security section to the foreword and a footnote to the gArmin Ronacherbefore adoption4671429
line 372why, one step back372 information.Heavily improved quickstart section.Armin Ronacherbefore adoption625eba4
lines 373–374why, one step back373374Updated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621
lines 375–383why, one step back375Accessing Request Data376----------------------377378For web applications it's crucial to react to the data a client sent to379the server. In Flask this information is provided by the global380:class:`~flask.request` object. If you have some experience with Python381you might be wondering how that object can be global and how Flask382manages to still be threadsafe. The answer are context locals:383Heavily improved quickstart section.Armin Ronacherbefore adoption625eba4
lines 384–386why, one step back384385.. _context-locals:386Updated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621
lines 387–533why, one step back387Context Locals388``````````````389390.. admonition:: Insider Information391392 If you want to understand how that works and how you can implement393 tests with context locals, read this section, otherwise just skip it.394395Certain objects in Flask are global objects, but not just a standard396global object, but actually a proxy to an object that is local to a397specific context. What a mouthful. But that is actually quite easy to398understand.399400Imagine the context being the handling thread. A request comes in and the401webserver decides to spawn a new thread (or something else, the402underlying object is capable of dealing with other concurrency systems403than threads as well). When Flask starts its internal request handling it404figures out that the current thread is the active context and binds the405current application and the WSGI environments to that context (thread).406It does that in an intelligent way that one application can invoke another407application without breaking.408409So what does this mean to you? Basically you can completely ignore that410this is the case unless you are unittesting or something different. You411will notice that code that depends on a request object will suddenly break412because there is no request object. The solution is creating a request413object yourself and binding it to the context. The easiest solution for414unittesting is by using the :meth:`~flask.Flask.test_request_context`415context manager. In combination with the `with` statement it will bind a416test request so that you can interact with it. Here an example::417418 from flask import request419420 with app.test_request_context('/hello', method='POST'):421 # now you can do something with the request until the422 # end of the with block, such as basic assertions:423 assert request.path == '/hello'424 assert request.method == 'POST'425426The other possibility is passing a whole WSGI environment to the427:meth:`~flask.Flask.request_context` method::428429 from flask import request430431 with app.request_context(environ):432 assert request.method == 'POST'433434The Request Object435``````````````````436437The request object is documented in the API section and we will not cover438it here in detail (see :class:`~flask.request`), but just mention some of439the most common operations. First of all you have to import it from the440the `flask` module::441442 from flask import request443444The current request method is available by using the445:attr:`~flask.request.method` attribute. To access form data (data446transmitted in a `POST` or `PUT` request) you can use the447:attr:`~flask.request.form` attribute. Here a full example of the two448attributes mentioned above::449450 @app.route('/login', method=['POST', 'GET'])451 def login():452 error = None453 if request.method == 'POST':454 if valid_login(request.form['username'],455 request.form['password']):456 return log_the_user_in(request.form['username'])457 else:458 error = 'Invalid username/password'459 # this is executed if the request method was GET or the460 # credentials were invalid461462What happens if the key does not exist in the `form` attribute? In that463case a special :exc:`KeyError` is raised. You can catch it like a464standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request465error page is shown instead. So for many situations you don't have to466deal with that problem.467468To access parameters submitted in the URL (``?key=value``) you can use the469:attr:`~flask.request.args` attribute::470471 searchword = request.args.get('q', '')472473We recommend accessing URL parameters with `get` or by catching the474`KeyError` because users might change the URL and presenting them a 400475bad request page in that case is a bit user unfriendly.476477For a full list of methods and attribtues on that object, head over to the478:class:`~flask.request` documentation.479480481File Uploads482````````````483484Obviously you can handle uploaded files with Flask just as easy. Just485make sure not to forget to set the ``enctype="multipart/form-data"``486attribtue on your HTML form, otherwise the browser will not transmit your487files at all.488489Uploaded files are stored in memory or at a temporary location on the490filesystem. You can access those files by looking at the491:attr:`~flask.request.files` attribute on the request object. Each492uploaded file is stored in that dictionary. It behaves just like a493standard Python :class:`file` object, but it also has a494:meth:`~werkzeug.FileStorage.save` method that allows you to store that495file on the filesystem of the server. Here a simple example how that496works::497498 from flask import request499500 @app.route('/upload', methods=['GET', 'POST'])501 def upload_file():502 if request.method == 'POST':503 f = request.files['the_file']504 f.save('/var/www/uploads/uploaded_file.txt')505 ...506507If you want to know how the file was named on the client before it was508uploaded to your application, you can access the509:attr:`~werkzeug.FileStorage.filename` attribute. However please keep in510mind that this value can be forged so never ever trust that value. If you511want to use the filename of the client to store the file on the server,512pass it through the :func:`~werkzeug.secure_filename` function that513Werkzeug provides for you::514515 from flask import request516 from werkzeug import secure_filename517518 @app.route('/upload', methods=['GET', 'POST'])519 def upload_file():520 if request.method == 'POST':521 f= request.files['the_file']522 f.save('/var/www/uploads/' + secure_filename(f.filename))523 ...524525Cookies526```````527528To access cookies you can use the :attr:`~flask.request.cookies`529attribute. Again this is a dictionary with all the cookies the client530transmits. If you want to use sessions, do not use the cookies directly531but instead use the :ref:`sessions` in Flask that add some security on top532of cookies for you.533Heavily improved quickstart section.Armin Ronacherbefore adoption625eba4
lines 534–564why, one step back534535Redirects and Errors536--------------------537538To redirect a user to somewhere else you can use the539:func:`~flask.redirect` function, to abort a request early with an error540code the :func:`~flask.abort` function. Here an example how this works::541542 from flask import abort, redirect, url_for543544 @app.route('/')545 def index():546 return redirect(url_for('login'))547548 @app.route('/login')549 def login():550 abort(401)551 this_is_never_executed()552553This is a rather pointless example because a user will be redirected from554the index to a page he cannot access (401 means access denied) but it555shows how that works.556557By default a black and white error page is shown for each error code. If558you want to customize the error page, you can use the559:meth:`~flask.Flask.errorhandler` decorator::560561 from flask import render_template562563 @app.errorhandler(404)564 def page_not_found(error):Another doc improvementArmin Ronacherbefore adoption6a3a046
lines 565–569why, one step back565 return render_template('page_not_found.html'), 404566567Note the ``404`` after the :func:`~flask.render_template` call. This568tells Flask that the status code of that page should be 404 which means569not found. By default 200 is assumed which translats to: all went well.Heavily improved quickstart section.Armin Ronacherbefore adoption625eba4
line 570why, one step back570Updated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621
lines 571–609why, one step back571.. _sessions:572573Sessions574--------575576Besides the request object there is also a second object called577:class:`~flask.session` that allows you to store information specific to a578user from one request to the next. This is implemented on top of cookies579for you and signes the cookies cryptographically. What this means is that580the user could look at the contents of your cookie but not modify it,581unless he knows the secret key used for signing.582583In order to use sessions you have to set a secret key. Here is how584sessions work::585586 from flask import session, redirect, url_for, escape587588 @app.route('/')589 def index():590 if 'username' in session:591 return 'Logged in as %s' % escape(session['username'])592 return 'You are not logged in'593594 @app.route('/login', methods=['GET', 'POST'])595 def login():596 if request.method == 'POST':597 session['username'] = request.form['username']598 return redirect(url_for('index'))599 return '''600 <form action="" method="post">601 <p><input type=text name=username>602 <p><input type=submit value=Login>603 </form>604 '''605606 @app.route('/logout')607 def logout():608 # remove the username from the session if its there609 session.pop('username', None)Heavily improved quickstart section.Armin Ronacherbefore adoption625eba4
line 610why, one step back610set secret key :)Armin Ronacherbefore adoption4e1b3e1
lines 611–613why, one step back611 # set the secret key. keep this really secret:612 app.secret_key = 'the secret key'613Linked escapeArmin Ronacherbefore adoption0b8e01b
lines 614–616why, one step back614The here mentioned :func:`~flask.escape` does escaping for you if you are615not using the template engine (like in this example).616Heavily improved quickstart section.Armin Ronacherbefore adoption625eba4
lines 617–627why, one step back617Message Flashing618----------------619620Good applications and user interfaces are all about feedback. If the user621does not get enough feedback he will probably end up hating the622application. Flask provides a really simple way to give feedback to a623user with the flashing system. The flashing system basically makes it624possible to record a message at the end of a request and access it next625request and only next request. This is usually combined with a layout626template that does this.627Flashing -> patterns documentationArmin Ronacherbefore adoptiona9d4ea8
lines 628–631why, one step back628To flash a message use the :func:`~flask.flash` method, to get hold of the629messages you can use :func:`~flask.get_flashed_messages` which is also630available in the templates. Check out the :ref:`message-flashing-pattern`631for a full example.