Skip to content
Myr

quickstart.rst

This file

Path

docs/quickstart.rst

603 lines · 21.5 KiB

Last changed by

Linked escapeArmin Ronacherbefore adoption0b8e01b

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.565758Debug 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.787980Routing81-------8283As you have seen above, the :meth:`~flask.Flask.route` decorator is used84to bind a function to a URL.  But there is more to it!  You can make85certain parts of the URL dynamic and attach multiple rules to a function.8687Here some examples::8889    @app.route('/')90    def index():91        return 'Index Page'9293    @app.route('/hello')94    def hello():95        return 'Hello World'969798Variable Rules99``````````````100101Modern web applications have beautiful URLs.  This helps people remember102the URLs which is especially handy for applications that are used from103mobile devices with slower network connections.  If the user can directly104go to the desired page without having to hit the index page it is more105likely he will like the page and come back next time.106107To add variable parts to a URL you can mark these special sections as108``<variable_name>``.  Such a part is then passed as keyword argument to109your function.  Optionally a converter can be specifed by specifying a110rule with ``<converter:variable_name>``.  Here some nice examples::111112    @app.route('/user/<username>')113    def show_user_profile(username):114        # show the user profile for that user115        pass116117    @app.route('/post/<int:post_id>')118    def show_post(post_id):119        # show the post with the given id, the id is an integer120        pass121122The following converters exist:123124=========== ===========================================125`int`       accepts integers126`float`     like `int` but for floating point values127`path`      like the default but also accepts slashes128=========== ===========================================129130URL Building131````````````132133If it can match URLs, can it also generate them?  Of course you can.  To134build a URL to a specific function you can use the :func:`~flask.url_for`135function.  It accepts the name of the function as first argument and a136number of keyword arguments, each corresponding to the variable part of137the URL rule.  Here some examples:138139>>> from flask import Flask, url_for140>>> app = Flask(__name__)141>>> @app.route('/')142... def index(): pass143... 144>>> @app.route('/login')145... def login(): pass146... 147>>> @app.route('/user/<username>')148... def profile(username): pass149... 150>>> with app.test_request_context():151...  print url_for('index')152...  print url_for('login')153...  print url_for('profile', username='John Doe')154... 155/156/login157/user/John%20Doe158159(This also uses the :meth:`~flask.Flask.test_request_context` method160explained below.  It basically tells flask to think we are handling a161request even though we are not, we are in an interactive Python shell.162Have a look at the explanation below. :ref:`context-locals`).163164Why would you want to build URLs instead of hardcoding them in your165templates?  There are three good reasons for this:1661671. reversing is often more descriptive than hardcoding the URLs.  Also and168   more importantly you can change URLs in one go without having to change169   the URLs all over the place.1702. URL building will handle escaping of special characters and unicode171   data transparently for you, you don't have to deal with that.1723. If your application is placed outside the URL root (so say in173   ``/myapplication`` instead of ``/``), :func:`~flask.url_for` will174   handle that properly for you.175176177HTTP Methods178````````````179180HTTP (the protocol web applications are speaking) knows different methods181to access URLs.  By default a route only answers to `GET` requests, but182that can be changed by providing the `methods` argument to the183:meth:`~flask.Flask.route` decorator.  Here some examples::184185    @app.route('/login', methods=['GET', 'POST'])186    def login():187        if request.method == 'POST':188            do_the_login()189        else:190            show_the_login_form()191192If `GET` is present, `HEAD` will be added automatically for you.  You193don't have to deal with that.  It will also make sure that `HEAD` requests194are handled like the `HTTP RFC`_ (the document describing the HTTP195protocol) demands, so you can completely ignore that part of the HTTP196specification.197198You have no idea what an HTTP method is?  Worry not, here quick199introduction in HTTP methods and why they matter:200201The HTTP method (also often called "the verb") tells the server what the202clients wants to *do* with the requested page.  The following methods are203very common:204205`GET`206    The Browser tells the server: just *get* me the information stored on207    that page and send them to me.  This is probably the most common208    method.209210`HEAD`211    The Browser tells the server: get me the information, but I am only212    interested in the *headers*, not the content of the page.  An213    application is supposed to handle that as if a `GET` request was214    received but not deliver the actual contents.  In Flask you don't have215    to deal with that at all, the underlying Werkzeug library handles that216    for you.217218`POST`219    The browser tells the server that it wants to *post* some new220    information to that URL and that the server must ensure the data is221    stored and only stored once.  This is how HTML forms are usually222    transmitting data to the server.223224`PUT`225    Similar to `POST` but the server might trigger the store procedure226    multiple times by overwriting the old values more than once.  Now you227    might be asking why this is any useful, but there are some good228    reasons to do that.  Consider the connection is lost during229    transmission, in that situation a system between the browser and the230    server might sent the request safely a second time without breaking231    things.  With `POST` that would not be possible because it must only232    be triggered once.233234`DELETE`235    Remove the information that the given location.236237Now the interesting part is that in HTML4 and XHTML1, the only methods a238form might submit to the server are `GET` and `POST`.  But with JavaScript239and future HTML standards you can use other methods as well.  Furthermore240HTTP became quite popular lately and there are more things than browsers241that are speaking HTTP.  (Your revision control system for instance might242speak HTTP)243244.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt245246Static Files247------------248249Dynamic web applications need static files as well.  That's usually where250the CSS and JavaScript files are coming from.  Ideally your web server is251configured to serve them for you, but during development Flask can do that252as well.  Just create a folder called `static` in your package or next to253your module and it will be available at `/static` on the application.254255To generate URLs to that part of the URL, use the special ``'static'`` URL256name::257258    url_for('static', filename='style.css')259260The file has to be stored on the filesystem as ``static/style.css``.261262Rendering Templates263-------------------264265Generating HTML from within Python is not fun, and actually pretty266cumbersome because you have to do the HTML escaping on your own to keep267the application secure.  Because of that Flask configures the `Jinja2268<http://jinja.pocoo.org/2/>`_ template engine for you automatically.269270To render a template you can use the :func:`~flask.render_template`271method.  All you have to do is to provide the name of the template and the272variables you want to pass to the template engine as keyword arguments.273Here a simple example of how to render a template::274275    from flask import render_template276277    @app.route('/hello/')278    @app.route('/hello/<name>')279    def hello(name=None):280        return render_template('hello.html', name=name)281282Flask will look for templates in the `templates` folder.  So if your283application is a module, that folder is next to that module, if it's a284pacakge it's actually inside your package:285286**Case 1**: a module::287    288    /application.py289    /templates290        /hello.html291292**Case 2**: a package::293294    /application295        /__init__.py296        /templates297            /hello.html298299For templates you can use the full power of Jinja2 templates.  Head over300to the `Jinja2 Template Documentation301<http://jinja.pocoo.org/2/documentation/templates>`_ for more information.302303Here an example template:304305.. sourcecode:: html+jinja306307    <!doctype html>308    <title>Hello from Flask</title>309    {% if name %}310      <h1>Hello {{ name }}!</h1>311    {% else %}312      <h1>Hello World!</h1>313    {% endif %}314315Inside templates you also have access to the :class:`~flask.request`,316:class:`~flask.session` and :class:`~flask.g` [#]_ objects317as well as the :func:`~flask.get_flashed_messages` function.318319Templates are especially useful if inheritance is used.  If you want to320know how that works, head over to the :ref:`template-inheritance` pattern321documentation.  Basically template inheritance makes it possible to keep322certain elements on each page (like header, navigation and footer).323324Automatic escaping is enabled, so if name contains HTML it will be escaped325automatically.  If you can trust a variable and you know that it will be326safe HTML (because for example it came from a module that converts wiki327markup to HTML) you can mark it as safe by using the328:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the329template.  Head over to the Jinja 2 documentation for more examples.330331Here a basic introduction in how the :class:`~jinja2.Markup` class works:332333>>> from flask import Markup334>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'335Markup(u'<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')336>>> Markup.escape('<blink>hacker</blink>')337Markup(u'&lt;blink&gt;hacker&lt;/blink&gt;')338>>> Markup('<em>Marked up</em> &raquo; HTML').striptags()339u'Marked up \xbb HTML'340341.. [#] Unsure what that :class:`~flask.g` object is? It's something you342   can store information on yourself, check the documentation of that343   object (:class:`~flask.g`) and the :ref:`database-pattern` for more344   information.345346347Accessing Request Data348----------------------349350For web applications it's crucial to react to the data a client sent to351the server.  In Flask this information is provided by the global352:class:`~flask.request` object.  If you have some experience with Python353you might be wondering how that object can be global and how Flask354manages to still be threadsafe.  The answer are context locals:355356357.. _context-locals:358359Context Locals360``````````````361362.. admonition:: Insider Information363364   If you want to understand how that works and how you can implement365   tests with context locals, read this section, otherwise just skip it.366367Certain objects in Flask are global objects, but not just a standard368global object, but actually a proxy to an object that is local to a369specific context.  What a mouthful.  But that is actually quite easy to370understand.371372Imagine the context being the handling thread.  A request comes in and the373webserver decides to spawn a new thread (or something else, the374underlying object is capable of dealing with other concurrency systems375than threads as well).  When Flask starts its internal request handling it376figures out that the current thread is the active context and binds the377current application and the WSGI environments to that context (thread).378It does that in an intelligent way that one application can invoke another379application without breaking.380381So what does this mean to you?  Basically you can completely ignore that382this is the case unless you are unittesting or something different.  You383will notice that code that depends on a request object will suddenly break384because there is no request object.  The solution is creating a request385object yourself and binding it to the context.  The easiest solution for386unittesting is by using the :meth:`~flask.Flask.test_request_context`387context manager.  In combination with the `with` statement it will bind a388test request so that you can interact with it.  Here an example::389390    from flask import request391392    with app.test_request_context('/hello', method='POST'):393        # now you can do something with the request until the394        # end of the with block, such as basic assertions:395        assert request.path == '/hello'396        assert request.method == 'POST'397398The other possibility is passing a whole WSGI environment to the399:meth:`~flask.Flask.request_context` method::400401    from flask import request402403    with app.request_context(environ):404        assert request.method == 'POST'405406The Request Object407``````````````````408409The request object is documented in the API section and we will not cover410it here in detail (see :class:`~flask.request`), but just mention some of411the most common operations.  First of all you have to import it from the412the `flask` module::413414    from flask import request415416The current request method is available by using the417:attr:`~flask.request.method` attribute.  To access form data (data418transmitted in a `POST` or `PUT` request) you can use the419:attr:`~flask.request.form` attribute.  Here a full example of the two420attributes mentioned above::421422    @app.route('/login', method=['POST', 'GET'])423    def login():424        error = None425        if request.method == 'POST':426            if valid_login(request.form['username'],427                           request.form['password']):428                return log_the_user_in(request.form['username'])429            else:430                error = 'Invalid username/password'431        # this is executed if the request method was GET or the432        # credentials were invalid433434What happens if the key does not exist in the `form` attribute?  In that435case a special :exc:`KeyError` is raised.  You can catch it like a436standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request437error page is shown instead.  So for many situations you don't have to438deal with that problem.439440To access parameters submitted in the URL (``?key=value``) you can use the441:attr:`~flask.request.args` attribute::442443    searchword = request.args.get('q', '')444445We recommend accessing URL parameters with `get` or by catching the446`KeyError` because users might change the URL and presenting them a 400447bad request page in that case is a bit user unfriendly.448449For a full list of methods and attribtues on that object, head over to the450:class:`~flask.request` documentation.451452453File Uploads454````````````455456Obviously you can handle uploaded files with Flask just as easy.  Just457make sure not to forget to set the ``enctype="multipart/form-data"``458attribtue on your HTML form, otherwise the browser will not transmit your459files at all.460461Uploaded files are stored in memory or at a temporary location on the462filesystem.  You can access those files by looking at the463:attr:`~flask.request.files` attribute on the request object.  Each464uploaded file is stored in that dictionary.  It behaves just like a465standard Python :class:`file` object, but it also has a466:meth:`~werkzeug.FileStorage.save` method that allows you to store that467file on the filesystem of the server.  Here a simple example how that468works::469470    from flask import request471472    @app.route('/upload', methods=['GET', 'POST'])473    def upload_file():474        if request.method == 'POST':475            f = request.files['the_file']476            f.save('/var/www/uploads/uploaded_file.txt')477        ...478479If you want to know how the file was named on the client before it was480uploaded to your application, you can access the481:attr:`~werkzeug.FileStorage.filename` attribute.  However please keep in482mind that this value can be forged so never ever trust that value.  If you483want to use the filename of the client to store the file on the server,484pass it through the :func:`~werkzeug.secure_filename` function that485Werkzeug provides for you::486487    from flask import request488    from werkzeug import secure_filename489490    @app.route('/upload', methods=['GET', 'POST'])491    def upload_file():492        if request.method == 'POST':493            f= request.files['the_file']494            f.save('/var/www/uploads/' + secure_filename(f.filename))495        ...496497Cookies498```````499500To access cookies you can use the :attr:`~flask.request.cookies`501attribute.  Again this is a dictionary with all the cookies the client502transmits.  If you want to use sessions, do not use the cookies directly503but instead use the :ref:`sessions` in Flask that add some security on top504of cookies for you.505506507Redirects and Errors508--------------------509510To redirect a user to somewhere else you can use the511:func:`~flask.redirect` function, to abort a request early with an error512code the :func:`~flask.abort` function.  Here an example how this works::513514    from flask import abort, redirect, url_for515516    @app.route('/')517    def index():518        return redirect(url_for('login'))519520    @app.route('/login')521    def login():522        abort(401)523        this_is_never_executed()524525This is a rather pointless example because a user will be redirected from526the index to a page he cannot access (401 means access denied) but it527shows how that works.528529By default a black and white error page is shown for each error code.  If530you want to customize the error page, you can use the531:meth:`~flask.Flask.errorhandler` decorator::532533    from flask import render_template534535    @app.errorhandler(404)536    def page_not_found(error):537        return render_template('page_not_found.html'), 404538539Note the ``404`` after the :func:`~flask.render_template` call.  This540tells Flask that the status code of that page should be 404 which means541not found.  By default 200 is assumed which translats to: all went well.542543.. _sessions:544545Sessions546--------547548Besides the request object there is also a second object called549:class:`~flask.session` that allows you to store information specific to a550user from one request to the next.  This is implemented on top of cookies551for you and signes the cookies cryptographically.  What this means is that552the user could look at the contents of your cookie but not modify it,553unless he knows the secret key used for signing.554555In order to use sessions you have to set a secret key.  Here is how556sessions work::557558    from flask import session, redirect, url_for, escape559560    @app.route('/')561    def index():562        if 'username' in session:563            return 'Logged in as %s' % escape(session['username'])564        return 'You are not logged in'565566    @app.route('/login', methods=['GET', 'POST'])567    def login():568        if request.method == 'POST':569            session['username'] = request.form['username']570            return redirect(url_for('index'))571        return '''572            <form action="" method="post">573                <p><input type=text name=username>574                <p><input type=submit value=Login>575            </form>576        '''577578    @app.route('/logout')579    def logout():580        # remove the username from the session if its there581        session.pop('username', None)582583    # set the secret key.  keep this really secret:584    app.secret_key = 'the secret key'585586The here mentioned :func:`~flask.escape` does escaping for you if you are587not using the template engine (like in this example).588589Message Flashing590----------------591592Good applications and user interfaces are all about feedback.  If the user593does not get enough feedback he will probably end up hating the594application.  Flask provides a really simple way to give feedback to a595user with the flashing system.  The flashing system basically makes it596possible to record a message at the end of a request and access it next597request and only next request.  This is usually combined with a layout598template that does this.599600To flash a message use the :func:`~flask.flash` method, to get hold of the601messages you can use :func:`~flask.get_flashed_messages` which is also602available in the templates.  Check out the :ref:`message-flashing-pattern`603for a full example.