Skip to content
Myr

quickstart.rst

This file

Path

docs/quickstart.rst

618 lines · 22.0 KiB

Last changed by

Better English.Armin Ronacherbefore adoptionebb07a0

History of this file

Take it

And finished documentation for most parts.Armin Ronacherbefore adoption727c701

lines 1–2why, one step back
1.. _quickstart:
2

Updated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621

lines 3–25why, one step back
3Quickstart
4==========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()25

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

line 26why, one step back
26Just save it as `hello.py` or something similar and run it with your

Fixed a bug in setup.pyArmin Ronacherbefore adoption574e81f

lines 27–30why, one step back
27Python 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–32why, one step back
31
32 $ python hello.py

flask uses 127.0.0.1 as host by default now. stupid chrome.Armin Ronacherbefore adoption00f87f6

line 33why, one step back
33 * Running on http://127.0.0.1:5000/

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

line 34why, one step back
34

flask uses 127.0.0.1 as host by default now. stupid chrome.Armin Ronacherbefore adoption00f87f6

line 35why, one step back
35Head over to `http://127.0.0.1:5000/ <http://127.0.0.1:5000/>`_, you should

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

line 36why, one step back
36see your hello world greeting.

Updated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621

lines 37–54why, one step back
37
38So 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.54

further improved documentationArmin Ronacherbefore adoptiondf929c6

line 55why, one step back
55To stop the server, hit control-C.

First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40

line 56why, one step back
56

further improved documentationArmin Ronacherbefore adoptiondf929c6

lines 57–78why, one step back
57
58Debug Mode59----------6061Now that :meth:`~flask.Flask.run` method is nice to start a local62development server, but you would have to restart it manually after each63change you do to code. That is not very nice and Flask can do better. If64you enable the debug support the server will reload itself on code changes65and also provide you with a helpful debugger if things go wrong.6667There are two ways to enable debugging. Either set that flag on the68applciation object::6970 app.debug = True71 app.run()7273Or pass it to run::7475 app.run(debug=True)7677Both will have exactly the same effect.78

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

lines 79–86why, one step back
79.. admonition:: Attention
8081 The interactive debugger however does not work in forking environments82 which makes it nearly impossible to use on production servers but the83 debugger still allows the execution of arbitrary code which makes it a84 major security risk and **must never be used on production machines**85 because of that.86

Added screenshot of the debugger to Flask docs. Flask now runs from theArmin Ronacherbefore adoption40e0024

lines 87–93why, one step back
87Screenshot of the debugger in action:
8889.. image:: _static/debugger.png90 :align: center91 :class: screenshot92 :alt: screenshot of debugger in action93

Updated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621

lines 94–144why, one step back
94
95Routing96-------9798As you have seen above, the :meth:`~flask.Flask.route` decorator is used99to bind a function to a URL. But there is more to it! You can make100certain parts of the URL dynamic and attach multiple rules to a function.101102Here some examples::103104 @app.route('/')105 def index():106 return 'Index Page'107108 @app.route('/hello')109 def hello():110 return 'Hello World'111112113Variable Rules114``````````````115116Modern web applications have beautiful URLs. This helps people remember117the URLs which is especially handy for applications that are used from118mobile devices with slower network connections. If the user can directly119go to the desired page without having to hit the index page it is more120likely he will like the page and come back next time.121122To add variable parts to a URL you can mark these special sections as123``<variable_name>``. Such a part is then passed as keyword argument to124your function. Optionally a converter can be specifed by specifying a125rule with ``<converter:variable_name>``. Here some nice examples::126127 @app.route('/user/<username>')128 def show_user_profile(username):129 # show the user profile for that user130 pass131132 @app.route('/post/<int:post_id>')133 def show_post(post_id):134 # show the post with the given id, the id is an integer135 pass136137The following converters exist:138139=========== ===========================================140`int` accepts integers141`float` like `int` but for floating point values142`path` like the default but also accepts slashes143=========== ===========================================144

Heavily improved quickstart section.Armin Ronacherbefore adoption625eba4

lines 145–146why, one step back
145URL Building
146````````````

Updated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621

line 147why, one step back
147

Heavily improved quickstart section.Armin Ronacherbefore adoption625eba4

lines 148–178why, one step back
148If it can match URLs, can it also generate them? Of course you can. To
149build a URL to a specific function you can use the :func:`~flask.url_for`150function. It accepts the name of the function as first argument and a151number of keyword arguments, each corresponding to the variable part of152the URL rule. Here some examples:153154>>> from flask import Flask, url_for155>>> app = Flask(__name__)156>>> @app.route('/')157... def index(): pass158... 159>>> @app.route('/login')160... def login(): pass161... 162>>> @app.route('/user/<username>')163... def profile(username): pass164... 165>>> with app.test_request_context():166... print url_for('index')167... print url_for('login')168... print url_for('profile', username='John Doe')169... 170/171/login172/user/John%20Doe173174(This also uses the :meth:`~flask.Flask.test_request_context` method175explained below. It basically tells flask to think we are handling a176request even though we are not, we are in an interactive Python shell.177Have a look at the explanation below. :ref:`context-locals`).178

Described HTTP methodsArmin Ronacherbefore adoption8171da8

lines 179–180why, one step back
179Why would you want to build URLs instead of hardcoding them in your
180templates? There are three good reasons for this:

Heavily improved quickstart section.Armin Ronacherbefore adoption625eba4

line 181why, one step back
181

Described HTTP methodsArmin Ronacherbefore adoption8171da8

lines 182–191why, one step back
1821. reversing is often more descriptive than hardcoding the URLs. Also and
183 more importantly you can change URLs in one go without having to change184 the URLs all over the place.1852. URL building will handle escaping of special characters and unicode186 data transparently for you, you don't have to deal with that.1873. If your application is placed outside the URL root (so say in188 ``/myapplication`` instead of ``/``), :func:`~flask.url_for` will189 handle that properly for you.190191

Updated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621

lines 192–194why, one step back
192HTTP Methods
193````````````194

Linked HTTPArmin Ronacherbefore adoption4e7aa9e

lines 195–198why, one step back
195HTTP (the protocol web applications are speaking) knows different methods
196to access URLs. By default a route only answers to `GET` requests, but197that can be changed by providing the `methods` argument to the198:meth:`~flask.Flask.route` decorator. Here some examples::

Updated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621

lines 199–206why, one step back
199
200 @app.route('/login', methods=['GET', 'POST'])201 def login():202 if request.method == 'POST':203 do_the_login()204 else:205 show_the_login_form()206

Linked HTTPArmin Ronacherbefore adoption4e7aa9e

lines 207–211why, one step back
207If `GET` is present, `HEAD` will be added automatically for you. You
208don't have to deal with that. It will also make sure that `HEAD` requests209are handled like the `HTTP RFC`_ (the document describing the HTTP210protocol) demands, so you can completely ignore that part of the HTTP211specification.

Described HTTP methodsArmin Ronacherbefore adoption8171da8

lines 212–235why, one step back
212
213You have no idea what an HTTP method is? Worry not, here quick214introduction in HTTP methods and why they matter:215216The HTTP method (also often called "the verb") tells the server what the217clients wants to *do* with the requested page. The following methods are218very common:219220`GET`221 The Browser tells the server: just *get* me the information stored on222 that page and send them to me. This is probably the most common223 method.224225`HEAD`226 The Browser tells the server: get me the information, but I am only227 interested in the *headers*, not the content of the page. An228 application is supposed to handle that as if a `GET` request was229 received but not deliver the actual contents. In Flask you don't have230 to deal with that at all, the underlying Werkzeug library handles that231 for you.232233`POST`234 The browser tells the server that it wants to *post* some new235 information to that URL and that the server must ensure the data is

might -> mustArmin Ronacherbefore adoption85ca089

lines 236–237why, one step back
236 stored and only stored once. This is how HTML forms are usually
237 transmitting data to the server.

Described HTTP methodsArmin Ronacherbefore adoption8171da8

lines 238–245why, one step back
238
239`PUT`240 Similar to `POST` but the server might trigger the store procedure241 multiple times by overwriting the old values more than once. Now you242 might be asking why this is any useful, but there are some good243 reasons to do that. Consider the connection is lost during244 transmission, in that situation a system between the browser and the245 server might sent the request safely a second time without breaking

might -> mustArmin Ronacherbefore adoption85ca089

line 246why, one step back
246 things. With `POST` that would not be possible because it must only

Described HTTP methodsArmin Ronacherbefore adoption8171da8

lines 247–257why, one step back
247 be triggered once.
248249`DELETE`250 Remove the information that the given location.251252Now the interesting part is that in HTML4 and XHTML1, the only methods a253form might submit to the server are `GET` and `POST`. But with JavaScript254and future HTML standards you can use other methods as well. Furthermore255HTTP became quite popular lately and there are more things than browsers256that are speaking HTTP. (Your revision control system for instance might257speak HTTP)

Linked HTTPArmin Ronacherbefore adoption4e7aa9e

lines 258–259why, one step back
258
259.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt

Updated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621

line 260why, one step back
260

And finished documentation for most parts.Armin Ronacherbefore adoption727c701

lines 261–276why, one step back
261Static Files
262------------263264Dynamic web applications need static files as well. That's usually where265the CSS and JavaScript files are coming from. Ideally your web server is266configured to serve them for you, but during development Flask can do that267as well. Just create a folder called `static` in your package or next to268your module and it will be available at `/static` on the application.269270To generate URLs to that part of the URL, use the special ``'static'`` URL271name::272273 url_for('static', filename='style.css')274275The file has to be stored on the filesystem as ``static/style.css``.276

Heavily improved quickstart section.Armin Ronacherbefore adoption625eba4

lines 277–278why, one step back
277Rendering Templates
278-------------------

Updated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621

line 279why, one step back
279

Heavily improved quickstart section.Armin Ronacherbefore adoption625eba4

lines 280–287why, one step back
280Generating HTML from within Python is not fun, and actually pretty
281cumbersome because you have to do the HTML escaping on your own to keep282the application secure. Because of that Flask configures the `Jinja2283<http://jinja.pocoo.org/2/>`_ template engine for you automatically.284285To render a template you can use the :func:`~flask.render_template`286method. All you have to do is to provide the name of the template and the287variables you want to pass to the template engine as keyword arguments.

Better English.Armin Ronacherbefore adoptionebb07a0

line 288why, one step back
288Here's a simple example of how to render a template::

Heavily improved quickstart section.Armin Ronacherbefore adoption625eba4

lines 289–330why, one step back
289
290 from flask import render_template291292 @app.route('/hello/')293 @app.route('/hello/<name>')294 def hello(name=None):295 return render_template('hello.html', name=name)296297Flask will look for templates in the `templates` folder. So if your298application is a module, that folder is next to that module, if it's a299pacakge it's actually inside your package:300301**Case 1**: a module::302 303 /application.py304 /templates305 /hello.html306307**Case 2**: a package::308309 /application310 /__init__.py311 /templates312 /hello.html313314For templates you can use the full power of Jinja2 templates. Head over315to the `Jinja2 Template Documentation316<http://jinja.pocoo.org/2/documentation/templates>`_ for more information.317318Here an example template:319320.. sourcecode:: html+jinja321322 <!doctype html>323 <title>Hello from Flask</title>324 {% if name %}325 <h1>Hello {{ name }}!</h1>326 {% else %}327 <h1>Hello World!</h1>328 {% endif %}329330Inside 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 331–332why, one step back
331:class:`~flask.session` and :class:`~flask.g` [#]_ objects
332as well as the :func:`~flask.get_flashed_messages` function.

And finished documentation for most parts.Armin Ronacherbefore adoption727c701

lines 333–337why, one step back
333
334Templates are especially useful if inheritance is used. If you want to335know how that works, head over to the :ref:`template-inheritance` pattern336documentation. Basically template inheritance makes it possible to keep337certain elements on each page (like header, navigation and footer).

Heavily improved quickstart section.Armin Ronacherbefore adoption625eba4

lines 338–354why, one step back
338
339Automatic escaping is enabled, so if name contains HTML it will be escaped340automatically. If you can trust a variable and you know that it will be341safe HTML (because for example it came from a module that converts wiki342markup to HTML) you can mark it as safe by using the343:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the344template. Head over to the Jinja 2 documentation for more examples.345346Here a basic introduction in how the :class:`~jinja2.Markup` class works:347348>>> from flask import Markup349>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'350Markup(u'<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')351>>> Markup.escape('<blink>hacker</blink>')352Markup(u'&lt;blink&gt;hacker&lt;/blink&gt;')353>>> Markup('<em>Marked up</em> &raquo; HTML').striptags()354u'Marked up \xbb HTML'

Added a security section to the foreword and a footnote to the gArmin Ronacherbefore adoption4671429

lines 355–357why, one step back
355
356.. [#] Unsure what that :class:`~flask.g` object is? It's something you357 can store information on yourself, check the documentation of that

Added WTForms documentation.Armin Ronacherbefore adoptionce18d45

line 358why, one step back
358 object (:class:`~flask.g`) and the :ref:`sqlite3` for more

Added a security section to the foreword and a footnote to the gArmin Ronacherbefore adoption4671429

line 359why, one step back
359 information.

Heavily improved quickstart section.Armin Ronacherbefore adoption625eba4

lines 360–361why, one step back
360
361

Updated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621

lines 362–370why, one step back
362Accessing Request Data
363----------------------364365For web applications it's crucial to react to the data a client sent to366the server. In Flask this information is provided by the global367:class:`~flask.request` object. If you have some experience with Python368you might be wondering how that object can be global and how Flask369manages to still be threadsafe. The answer are context locals:370

Heavily improved quickstart section.Armin Ronacherbefore adoption625eba4

lines 371–373why, one step back
371
372.. _context-locals:373

Updated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621

lines 374–520why, one step back
374Context Locals
375``````````````376377.. admonition:: Insider Information378379 If you want to understand how that works and how you can implement380 tests with context locals, read this section, otherwise just skip it.381382Certain objects in Flask are global objects, but not just a standard383global object, but actually a proxy to an object that is local to a384specific context. What a mouthful. But that is actually quite easy to385understand.386387Imagine the context being the handling thread. A request comes in and the388webserver decides to spawn a new thread (or something else, the389underlying object is capable of dealing with other concurrency systems390than threads as well). When Flask starts its internal request handling it391figures out that the current thread is the active context and binds the392current application and the WSGI environments to that context (thread).393It does that in an intelligent way that one application can invoke another394application without breaking.395396So what does this mean to you? Basically you can completely ignore that397this is the case unless you are unittesting or something different. You398will notice that code that depends on a request object will suddenly break399because there is no request object. The solution is creating a request400object yourself and binding it to the context. The easiest solution for401unittesting is by using the :meth:`~flask.Flask.test_request_context`402context manager. In combination with the `with` statement it will bind a403test request so that you can interact with it. Here an example::404405 from flask import request406407 with app.test_request_context('/hello', method='POST'):408 # now you can do something with the request until the409 # end of the with block, such as basic assertions:410 assert request.path == '/hello'411 assert request.method == 'POST'412413The other possibility is passing a whole WSGI environment to the414:meth:`~flask.Flask.request_context` method::415416 from flask import request417418 with app.request_context(environ):419 assert request.method == 'POST'420421The Request Object422``````````````````423424The request object is documented in the API section and we will not cover425it here in detail (see :class:`~flask.request`), but just mention some of426the most common operations. First of all you have to import it from the427the `flask` module::428429 from flask import request430431The current request method is available by using the432:attr:`~flask.request.method` attribute. To access form data (data433transmitted in a `POST` or `PUT` request) you can use the434:attr:`~flask.request.form` attribute. Here a full example of the two435attributes mentioned above::436437 @app.route('/login', method=['POST', 'GET'])438 def login():439 error = None440 if request.method == 'POST':441 if valid_login(request.form['username'],442 request.form['password']):443 return log_the_user_in(request.form['username'])444 else:445 error = 'Invalid username/password'446 # this is executed if the request method was GET or the447 # credentials were invalid448449What happens if the key does not exist in the `form` attribute? In that450case a special :exc:`KeyError` is raised. You can catch it like a451standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request452error page is shown instead. So for many situations you don't have to453deal with that problem.454455To access parameters submitted in the URL (``?key=value``) you can use the456:attr:`~flask.request.args` attribute::457458 searchword = request.args.get('q', '')459460We recommend accessing URL parameters with `get` or by catching the461`KeyError` because users might change the URL and presenting them a 400462bad request page in that case is a bit user unfriendly.463464For a full list of methods and attribtues on that object, head over to the465:class:`~flask.request` documentation.466467468File Uploads469````````````470471Obviously you can handle uploaded files with Flask just as easy. Just472make sure not to forget to set the ``enctype="multipart/form-data"``473attribtue on your HTML form, otherwise the browser will not transmit your474files at all.475476Uploaded files are stored in memory or at a temporary location on the477filesystem. You can access those files by looking at the478:attr:`~flask.request.files` attribute on the request object. Each479uploaded file is stored in that dictionary. It behaves just like a480standard Python :class:`file` object, but it also has a481:meth:`~werkzeug.FileStorage.save` method that allows you to store that482file on the filesystem of the server. Here a simple example how that483works::484485 from flask import request486487 @app.route('/upload', methods=['GET', 'POST'])488 def upload_file():489 if request.method == 'POST':490 f = request.files['the_file']491 f.save('/var/www/uploads/uploaded_file.txt')492 ...493494If you want to know how the file was named on the client before it was495uploaded to your application, you can access the496:attr:`~werkzeug.FileStorage.filename` attribute. However please keep in497mind that this value can be forged so never ever trust that value. If you498want to use the filename of the client to store the file on the server,499pass it through the :func:`~werkzeug.secure_filename` function that500Werkzeug provides for you::501502 from flask import request503 from werkzeug import secure_filename504505 @app.route('/upload', methods=['GET', 'POST'])506 def upload_file():507 if request.method == 'POST':508 f= request.files['the_file']509 f.save('/var/www/uploads/' + secure_filename(f.filename))510 ...511512Cookies513```````514515To access cookies you can use the :attr:`~flask.request.cookies`516attribute. Again this is a dictionary with all the cookies the client517transmits. If you want to use sessions, do not use the cookies directly518but instead use the :ref:`sessions` in Flask that add some security on top519of cookies for you.520

Heavily improved quickstart section.Armin Ronacherbefore adoption625eba4

lines 521–551why, one step back
521
522Redirects and Errors523--------------------524525To redirect a user to somewhere else you can use the526:func:`~flask.redirect` function, to abort a request early with an error527code the :func:`~flask.abort` function. Here an example how this works::528529 from flask import abort, redirect, url_for530531 @app.route('/')532 def index():533 return redirect(url_for('login'))534535 @app.route('/login')536 def login():537 abort(401)538 this_is_never_executed()539540This is a rather pointless example because a user will be redirected from541the index to a page he cannot access (401 means access denied) but it542shows how that works.543544By default a black and white error page is shown for each error code. If545you want to customize the error page, you can use the546:meth:`~flask.Flask.errorhandler` decorator::547548 from flask import render_template549550 @app.errorhandler(404)551 def page_not_found(error):

Another doc improvementArmin Ronacherbefore adoption6a3a046

lines 552–556why, one step back
552 return render_template('page_not_found.html'), 404
553554Note the ``404`` after the :func:`~flask.render_template` call. This555tells Flask that the status code of that page should be 404 which means556not found. By default 200 is assumed which translats to: all went well.

Heavily improved quickstart section.Armin Ronacherbefore adoption625eba4

line 557why, one step back
557

Updated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621

lines 558–596why, one step back
558.. _sessions:
559560Sessions561--------562563Besides the request object there is also a second object called564:class:`~flask.session` that allows you to store information specific to a565user from one request to the next. This is implemented on top of cookies566for you and signes the cookies cryptographically. What this means is that567the user could look at the contents of your cookie but not modify it,568unless he knows the secret key used for signing.569570In order to use sessions you have to set a secret key. Here is how571sessions work::572573 from flask import session, redirect, url_for, escape574575 @app.route('/')576 def index():577 if 'username' in session:578 return 'Logged in as %s' % escape(session['username'])579 return 'You are not logged in'580581 @app.route('/login', methods=['GET', 'POST'])582 def login():583 if request.method == 'POST':584 session['username'] = request.form['username']585 return redirect(url_for('index'))586 return '''587 <form action="" method="post">588 <p><input type=text name=username>589 <p><input type=submit value=Login>590 </form>591 '''592593 @app.route('/logout')594 def logout():595 # remove the username from the session if its there596 session.pop('username', None)

Heavily improved quickstart section.Armin Ronacherbefore adoption625eba4

line 597why, one step back
597

set secret key :)Armin Ronacherbefore adoption4e1b3e1

lines 598–600why, one step back
598 # set the secret key. keep this really secret:
599 app.secret_key = 'the secret key'600

Linked escapeArmin Ronacherbefore adoption0b8e01b

lines 601–603why, one step back
601The here mentioned :func:`~flask.escape` does escaping for you if you are
602not using the template engine (like in this example).603

Heavily improved quickstart section.Armin Ronacherbefore adoption625eba4

lines 604–614why, one step back
604Message Flashing
605----------------606607Good applications and user interfaces are all about feedback. If the user608does not get enough feedback he will probably end up hating the609application. Flask provides a really simple way to give feedback to a610user with the flashing system. The flashing system basically makes it611possible to record a message at the end of a request and access it next612request and only next request. This is usually combined with a layout613template that does this.614

Flashing -> patterns documentationArmin Ronacherbefore adoptiona9d4ea8

lines 615–618why, one step back
615To flash a message use the :func:`~flask.flash` method, to get hold of the
616messages you can use :func:`~flask.get_flashed_messages` which is also617available in the templates. Check out the :ref:`message-flashing-pattern`618for a full example.