Skip to content
Myr

quickstart.rst

This file

Path

docs/quickstart.rst

616 lines · 21.9 KiB

Last changed by

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

History of this file

Take it

1.. _quickstart:23Quickstart4==========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()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://localhost:5000/3435Head over to `http://localhost:5000/ <http://localhost:5000/>`_, you should36see your hello world greeting.3738So what did that code do?39401. first we imported the :class:`~flask.Flask` class.  An instance of this41   class will be our WSGI application.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.5455To stop the server, hit control-C.5657.. 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')697071Debug 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.919293Routing94-------9596As you have seen above, the :meth:`~flask.Flask.route` decorator is used97to bind a function to a URL.  But there is more to it!  You can make98certain parts of the URL dynamic and attach multiple rules to a function.99100Here some examples::101102    @app.route('/')103    def index():104        return 'Index Page'105106    @app.route('/hello')107    def hello():108        return 'Hello World'109110111Variable Rules112``````````````113114Modern web applications have beautiful URLs.  This helps people remember115the URLs which is especially handy for applications that are used from116mobile devices with slower network connections.  If the user can directly117go to the desired page without having to hit the index page it is more118likely he will like the page and come back next time.119120To add variable parts to a URL you can mark these special sections as121``<variable_name>``.  Such a part is then passed as keyword argument to122your function.  Optionally a converter can be specifed by specifying a123rule with ``<converter:variable_name>``.  Here some nice examples::124125    @app.route('/user/<username>')126    def show_user_profile(username):127        # show the user profile for that user128        pass129130    @app.route('/post/<int:post_id>')131    def show_post(post_id):132        # show the post with the given id, the id is an integer133        pass134135The following converters exist:136137=========== ===========================================138`int`       accepts integers139`float`     like `int` but for floating point values140`path`      like the default but also accepts slashes141=========== ===========================================142143URL Building144````````````145146If it can match URLs, can it also generate them?  Of course you can.  To147build a URL to a specific function you can use the :func:`~flask.url_for`148function.  It accepts the name of the function as first argument and a149number of keyword arguments, each corresponding to the variable part of150the URL rule.  Here some examples:151152>>> from flask import Flask, url_for153>>> app = Flask(__name__)154>>> @app.route('/')155... def index(): pass156... 157>>> @app.route('/login')158... def login(): pass159... 160>>> @app.route('/user/<username>')161... def profile(username): pass162... 163>>> with app.test_request_context():164...  print url_for('index')165...  print url_for('login')166...  print url_for('profile', username='John Doe')167... 168/169/login170/user/John%20Doe171172(This also uses the :meth:`~flask.Flask.test_request_context` method173explained below.  It basically tells flask to think we are handling a174request even though we are not, we are in an interactive Python shell.175Have a look at the explanation below. :ref:`context-locals`).176177Why would you want to build URLs instead of hardcoding them in your178templates?  There are three good reasons for this:1791801. reversing is often more descriptive than hardcoding the URLs.  Also and181   more importantly you can change URLs in one go without having to change182   the URLs all over the place.1832. URL building will handle escaping of special characters and unicode184   data transparently for you, you don't have to deal with that.1853. If your application is placed outside the URL root (so say in186   ``/myapplication`` instead of ``/``), :func:`~flask.url_for` will187   handle that properly for you.188189190HTTP Methods191````````````192193HTTP (the protocol web applications are speaking) knows different methods194to access URLs.  By default a route only answers to `GET` requests, but195that can be changed by providing the `methods` argument to the196:meth:`~flask.Flask.route` decorator.  Here some examples::197198    @app.route('/login', methods=['GET', 'POST'])199    def login():200        if request.method == 'POST':201            do_the_login()202        else:203            show_the_login_form()204205If `GET` is present, `HEAD` will be added automatically for you.  You206don't have to deal with that.  It will also make sure that `HEAD` requests207are handled like the `HTTP RFC`_ (the document describing the HTTP208protocol) demands, so you can completely ignore that part of the HTTP209specification.210211You have no idea what an HTTP method is?  Worry not, here quick212introduction in HTTP methods and why they matter:213214The HTTP method (also often called "the verb") tells the server what the215clients wants to *do* with the requested page.  The following methods are216very common:217218`GET`219    The Browser tells the server: just *get* me the information stored on220    that page and send them to me.  This is probably the most common221    method.222223`HEAD`224    The Browser tells the server: get me the information, but I am only225    interested in the *headers*, not the content of the page.  An226    application is supposed to handle that as if a `GET` request was227    received but not deliver the actual contents.  In Flask you don't have228    to deal with that at all, the underlying Werkzeug library handles that229    for you.230231`POST`232    The browser tells the server that it wants to *post* some new233    information to that URL and that the server must ensure the data is234    stored and only stored once.  This is how HTML forms are usually235    transmitting data to the server.236237`PUT`238    Similar to `POST` but the server might trigger the store procedure239    multiple times by overwriting the old values more than once.  Now you240    might be asking why this is any useful, but there are some good241    reasons to do that.  Consider the connection is lost during242    transmission, in that situation a system between the browser and the243    server might sent the request safely a second time without breaking244    things.  With `POST` that would not be possible because it must only245    be triggered once.246247`DELETE`248    Remove the information that the given location.249250Now the interesting part is that in HTML4 and XHTML1, the only methods a251form might submit to the server are `GET` and `POST`.  But with JavaScript252and future HTML standards you can use other methods as well.  Furthermore253HTTP became quite popular lately and there are more things than browsers254that are speaking HTTP.  (Your revision control system for instance might255speak HTTP)256257.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt258259Static Files260------------261262Dynamic web applications need static files as well.  That's usually where263the CSS and JavaScript files are coming from.  Ideally your web server is264configured to serve them for you, but during development Flask can do that265as well.  Just create a folder called `static` in your package or next to266your module and it will be available at `/static` on the application.267268To generate URLs to that part of the URL, use the special ``'static'`` URL269name::270271    url_for('static', filename='style.css')272273The file has to be stored on the filesystem as ``static/style.css``.274275Rendering Templates276-------------------277278Generating HTML from within Python is not fun, and actually pretty279cumbersome because you have to do the HTML escaping on your own to keep280the application secure.  Because of that Flask configures the `Jinja2281<http://jinja.pocoo.org/2/>`_ template engine for you automatically.282283To render a template you can use the :func:`~flask.render_template`284method.  All you have to do is to provide the name of the template and the285variables you want to pass to the template engine as keyword arguments.286Here a simple example of how to render a template::287288    from flask import render_template289290    @app.route('/hello/')291    @app.route('/hello/<name>')292    def hello(name=None):293        return render_template('hello.html', name=name)294295Flask will look for templates in the `templates` folder.  So if your296application is a module, that folder is next to that module, if it's a297pacakge it's actually inside your package:298299**Case 1**: a module::300    301    /application.py302    /templates303        /hello.html304305**Case 2**: a package::306307    /application308        /__init__.py309        /templates310            /hello.html311312For templates you can use the full power of Jinja2 templates.  Head over313to the `Jinja2 Template Documentation314<http://jinja.pocoo.org/2/documentation/templates>`_ for more information.315316Here an example template:317318.. sourcecode:: html+jinja319320    <!doctype html>321    <title>Hello from Flask</title>322    {% if name %}323      <h1>Hello {{ name }}!</h1>324    {% else %}325      <h1>Hello World!</h1>326    {% endif %}327328Inside templates you also have access to the :class:`~flask.request`,329:class:`~flask.session` and :class:`~flask.g` [#]_ objects330as well as the :func:`~flask.get_flashed_messages` function.331332Templates are especially useful if inheritance is used.  If you want to333know how that works, head over to the :ref:`template-inheritance` pattern334documentation.  Basically template inheritance makes it possible to keep335certain elements on each page (like header, navigation and footer).336337Automatic escaping is enabled, so if name contains HTML it will be escaped338automatically.  If you can trust a variable and you know that it will be339safe HTML (because for example it came from a module that converts wiki340markup to HTML) you can mark it as safe by using the341:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the342template.  Head over to the Jinja 2 documentation for more examples.343344Here a basic introduction in how the :class:`~jinja2.Markup` class works:345346>>> from flask import Markup347>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'348Markup(u'<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')349>>> Markup.escape('<blink>hacker</blink>')350Markup(u'&lt;blink&gt;hacker&lt;/blink&gt;')351>>> Markup('<em>Marked up</em> &raquo; HTML').striptags()352u'Marked up \xbb HTML'353354.. [#] Unsure what that :class:`~flask.g` object is? It's something you355   can store information on yourself, check the documentation of that356   object (:class:`~flask.g`) and the :ref:`database-pattern` for more357   information.358359360Accessing Request Data361----------------------362363For web applications it's crucial to react to the data a client sent to364the server.  In Flask this information is provided by the global365:class:`~flask.request` object.  If you have some experience with Python366you might be wondering how that object can be global and how Flask367manages to still be threadsafe.  The answer are context locals:368369370.. _context-locals:371372Context Locals373``````````````374375.. admonition:: Insider Information376377   If you want to understand how that works and how you can implement378   tests with context locals, read this section, otherwise just skip it.379380Certain objects in Flask are global objects, but not just a standard381global object, but actually a proxy to an object that is local to a382specific context.  What a mouthful.  But that is actually quite easy to383understand.384385Imagine the context being the handling thread.  A request comes in and the386webserver decides to spawn a new thread (or something else, the387underlying object is capable of dealing with other concurrency systems388than threads as well).  When Flask starts its internal request handling it389figures out that the current thread is the active context and binds the390current application and the WSGI environments to that context (thread).391It does that in an intelligent way that one application can invoke another392application without breaking.393394So what does this mean to you?  Basically you can completely ignore that395this is the case unless you are unittesting or something different.  You396will notice that code that depends on a request object will suddenly break397because there is no request object.  The solution is creating a request398object yourself and binding it to the context.  The easiest solution for399unittesting is by using the :meth:`~flask.Flask.test_request_context`400context manager.  In combination with the `with` statement it will bind a401test request so that you can interact with it.  Here an example::402403    from flask import request404405    with app.test_request_context('/hello', method='POST'):406        # now you can do something with the request until the407        # end of the with block, such as basic assertions:408        assert request.path == '/hello'409        assert request.method == 'POST'410411The other possibility is passing a whole WSGI environment to the412:meth:`~flask.Flask.request_context` method::413414    from flask import request415416    with app.request_context(environ):417        assert request.method == 'POST'418419The Request Object420``````````````````421422The request object is documented in the API section and we will not cover423it here in detail (see :class:`~flask.request`), but just mention some of424the most common operations.  First of all you have to import it from the425the `flask` module::426427    from flask import request428429The current request method is available by using the430:attr:`~flask.request.method` attribute.  To access form data (data431transmitted in a `POST` or `PUT` request) you can use the432:attr:`~flask.request.form` attribute.  Here a full example of the two433attributes mentioned above::434435    @app.route('/login', method=['POST', 'GET'])436    def login():437        error = None438        if request.method == 'POST':439            if valid_login(request.form['username'],440                           request.form['password']):441                return log_the_user_in(request.form['username'])442            else:443                error = 'Invalid username/password'444        # this is executed if the request method was GET or the445        # credentials were invalid446447What happens if the key does not exist in the `form` attribute?  In that448case a special :exc:`KeyError` is raised.  You can catch it like a449standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request450error page is shown instead.  So for many situations you don't have to451deal with that problem.452453To access parameters submitted in the URL (``?key=value``) you can use the454:attr:`~flask.request.args` attribute::455456    searchword = request.args.get('q', '')457458We recommend accessing URL parameters with `get` or by catching the459`KeyError` because users might change the URL and presenting them a 400460bad request page in that case is a bit user unfriendly.461462For a full list of methods and attribtues on that object, head over to the463:class:`~flask.request` documentation.464465466File Uploads467````````````468469Obviously you can handle uploaded files with Flask just as easy.  Just470make sure not to forget to set the ``enctype="multipart/form-data"``471attribtue on your HTML form, otherwise the browser will not transmit your472files at all.473474Uploaded files are stored in memory or at a temporary location on the475filesystem.  You can access those files by looking at the476:attr:`~flask.request.files` attribute on the request object.  Each477uploaded file is stored in that dictionary.  It behaves just like a478standard Python :class:`file` object, but it also has a479:meth:`~werkzeug.FileStorage.save` method that allows you to store that480file on the filesystem of the server.  Here a simple example how that481works::482483    from flask import request484485    @app.route('/upload', methods=['GET', 'POST'])486    def upload_file():487        if request.method == 'POST':488            f = request.files['the_file']489            f.save('/var/www/uploads/uploaded_file.txt')490        ...491492If you want to know how the file was named on the client before it was493uploaded to your application, you can access the494:attr:`~werkzeug.FileStorage.filename` attribute.  However please keep in495mind that this value can be forged so never ever trust that value.  If you496want to use the filename of the client to store the file on the server,497pass it through the :func:`~werkzeug.secure_filename` function that498Werkzeug provides for you::499500    from flask import request501    from werkzeug import secure_filename502503    @app.route('/upload', methods=['GET', 'POST'])504    def upload_file():505        if request.method == 'POST':506            f= request.files['the_file']507            f.save('/var/www/uploads/' + secure_filename(f.filename))508        ...509510Cookies511```````512513To access cookies you can use the :attr:`~flask.request.cookies`514attribute.  Again this is a dictionary with all the cookies the client515transmits.  If you want to use sessions, do not use the cookies directly516but instead use the :ref:`sessions` in Flask that add some security on top517of cookies for you.518519520Redirects and Errors521--------------------522523To redirect a user to somewhere else you can use the524:func:`~flask.redirect` function, to abort a request early with an error525code the :func:`~flask.abort` function.  Here an example how this works::526527    from flask import abort, redirect, url_for528529    @app.route('/')530    def index():531        return redirect(url_for('login'))532533    @app.route('/login')534    def login():535        abort(401)536        this_is_never_executed()537538This is a rather pointless example because a user will be redirected from539the index to a page he cannot access (401 means access denied) but it540shows how that works.541542By default a black and white error page is shown for each error code.  If543you want to customize the error page, you can use the544:meth:`~flask.Flask.errorhandler` decorator::545546    from flask import render_template547548    @app.errorhandler(404)549    def page_not_found(error):550        return render_template('page_not_found.html'), 404551552Note the ``404`` after the :func:`~flask.render_template` call.  This553tells Flask that the status code of that page should be 404 which means554not found.  By default 200 is assumed which translats to: all went well.555556.. _sessions:557558Sessions559--------560561Besides the request object there is also a second object called562:class:`~flask.session` that allows you to store information specific to a563user from one request to the next.  This is implemented on top of cookies564for you and signes the cookies cryptographically.  What this means is that565the user could look at the contents of your cookie but not modify it,566unless he knows the secret key used for signing.567568In order to use sessions you have to set a secret key.  Here is how569sessions work::570571    from flask import session, redirect, url_for, escape572573    @app.route('/')574    def index():575        if 'username' in session:576            return 'Logged in as %s' % escape(session['username'])577        return 'You are not logged in'578579    @app.route('/login', methods=['GET', 'POST'])580    def login():581        if request.method == 'POST':582            session['username'] = request.form['username']583            return redirect(url_for('index'))584        return '''585            <form action="" method="post">586                <p><input type=text name=username>587                <p><input type=submit value=Login>588            </form>589        '''590591    @app.route('/logout')592    def logout():593        # remove the username from the session if its there594        session.pop('username', None)595596    # set the secret key.  keep this really secret:597    app.secret_key = 'the secret key'598599The here mentioned :func:`~flask.escape` does escaping for you if you are600not using the template engine (like in this example).601602Message Flashing603----------------604605Good applications and user interfaces are all about feedback.  If the user606does not get enough feedback he will probably end up hating the607application.  Flask provides a really simple way to give feedback to a608user with the flashing system.  The flashing system basically makes it609possible to record a message at the end of a request and access it next610request and only next request.  This is usually combined with a layout611template that does this.612613To flash a message use the :func:`~flask.flash` method, to get hold of the614messages you can use :func:`~flask.get_flashed_messages` which is also615available in the templates.  Check out the :ref:`message-flashing-pattern`616for a full example.