Skip to content
Myr

quickstart.rst

This file

Path

docs/quickstart.rst

715 lines · 25.5 KiB

Last changed by

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption223d44d

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://127.0.0.1:5000/3435Head over to `http://127.0.0.1:5000/ <http://127.0.0.1:5000/>`_, you should36see your hello world greeting.3738So what did that code do?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.. _public-server:5859.. admonition:: Externally Visible Server6061   If you run the server you will notice that the server is only available62   from your own computer, not from any other in the network.  This is the63   default because in debugging mode a user of the application can execute64   arbitrary Python code on your computer.  If you have `debug` disabled65   or trust the users on your network, you can make the server publicly66   available.6768   Just change the call of the :meth:`~flask.Flask.run` method to look69   like this::7071       app.run(host='0.0.0.0')7273   This tells your operating system to listen on a public IP.747576Debug Mode77----------7879Now that :meth:`~flask.Flask.run` method is nice to start a local80development server, but you would have to restart it manually after each81change you do to code.  That is not very nice and Flask can do better.  If82you enable the debug support the server will reload itself on code changes83and also provide you with a helpful debugger if things go wrong.8485There are two ways to enable debugging.  Either set that flag on the86application object::8788    app.debug = True89    app.run()9091Or pass it to run::9293    app.run(debug=True)9495Both will have exactly the same effect.9697.. admonition:: Attention9899   The interactive debugger however does not work in forking environments100   which makes it nearly impossible to use on production servers but the101   debugger still allows the execution of arbitrary code which makes it a102   major security risk and **must never be used on production machines**103   because of that.104105Screenshot of the debugger in action:106107.. image:: _static/debugger.png108   :align: center109   :class: screenshot110   :alt: screenshot of debugger in action111112113Routing114-------115116As you have seen above, the :meth:`~flask.Flask.route` decorator is used117to bind a function to a URL.  But there is more to it!  You can make118certain parts of the URL dynamic and attach multiple rules to a function.119120Here some examples::121122    @app.route('/')123    def index():124        return 'Index Page'125126    @app.route('/hello')127    def hello():128        return 'Hello World'129130131Variable Rules132``````````````133134Modern web applications have beautiful URLs.  This helps people remember135the URLs which is especially handy for applications that are used from136mobile devices with slower network connections.  If the user can directly137go to the desired page without having to hit the index page it is more138likely he will like the page and come back next time.139140To add variable parts to a URL you can mark these special sections as141``<variable_name>``.  Such a part is then passed as keyword argument to142your function.  Optionally a converter can be specified by specifying a143rule with ``<converter:variable_name>``.  Here some nice examples::144145    @app.route('/user/<username>')146    def show_user_profile(username):147        # show the user profile for that user148        pass149150    @app.route('/post/<int:post_id>')151    def show_post(post_id):152        # show the post with the given id, the id is an integer153        pass154155The following converters exist:156157=========== ===========================================158`int`       accepts integers159`float`     like `int` but for floating point values160`path`      like the default but also accepts slashes161=========== ===========================================162163.. admonition:: Unique URLs / Redirection Behaviour164165   Flask's URL rules are based on Werkzeug's routing module.  The idea166   behind that module is to ensure nice looking and also unique URLs based167   on behaviour Apache and earlier servers coined.168169   Take these two rules::170171        @app.route('/projects/')172        def projects():173            pass174175        @app.route('/about')176        def about():177            pass178179   They look rather similar, the difference is the trailing slash in the180   URL *definition*.  In the first case, the canonical URL for the181   `projects` endpoint has a trailing slash.  It's similar to a folder in182   that sense.  Accessing it without a trailing slash will cause Flask to183   redirect to the canonical URL with the trailing slash.184185   However in the second case the URL is defined without a slash so it186   behaves similar to a file and accessing the URL with a trailing slash187   will be a 404 error.188189   Why is this?  This allows relative URLs to continue working if users190   access the page when they forget a trailing slash.  This behaviour is191   also consistent with how Apache and other servers work.  Also, the URLs192   will stay unique which helps search engines not indexing the same page193   twice.194195196.. _url-building:197198URL Building199````````````200201If it can match URLs, can it also generate them?  Of course you can.  To202build a URL to a specific function you can use the :func:`~flask.url_for`203function.  It accepts the name of the function as first argument and a204number of keyword arguments, each corresponding to the variable part of205the URL rule.  Unknown variable parts are appended to the URL as query206parameter.  Here some examples:207208>>> from flask import Flask, url_for209>>> app = Flask(__name__)210>>> @app.route('/')211... def index(): pass212...213>>> @app.route('/login')214... def login(): pass215...216>>> @app.route('/user/<username>')217... def profile(username): pass218...219>>> with app.test_request_context():220...  print url_for('index')221...  print url_for('login')222...  print url_for('login', next='/')223...  print url_for('profile', username='John Doe')224...225/226/login227/login?next=/228/user/John%20Doe229230(This also uses the :meth:`~flask.Flask.test_request_context` method231explained below.  It basically tells flask to think we are handling a232request even though we are not, we are in an interactive Python shell.233Have a look at the explanation below. :ref:`context-locals`).234235Why would you want to build URLs instead of hardcoding them in your236templates?  There are three good reasons for this:2372381. reversing is often more descriptive than hardcoding the URLs.  Also and239   more importantly you can change URLs in one go without having to change240   the URLs all over the place.2412. URL building will handle escaping of special characters and Unicode242   data transparently for you, you don't have to deal with that.2433. If your application is placed outside the URL root (so say in244   ``/myapplication`` instead of ``/``), :func:`~flask.url_for` will245   handle that properly for you.246247248HTTP Methods249````````````250251HTTP (the protocol web applications are speaking) knows different methods252to access URLs.  By default a route only answers to `GET` requests, but253that can be changed by providing the `methods` argument to the254:meth:`~flask.Flask.route` decorator.  Here some examples::255256    @app.route('/login', methods=['GET', 'POST'])257    def login():258        if request.method == 'POST':259            do_the_login()260        else:261            show_the_login_form()262263If `GET` is present, `HEAD` will be added automatically for you.  You264don't have to deal with that.  It will also make sure that `HEAD` requests265are handled like the `HTTP RFC`_ (the document describing the HTTP266protocol) demands, so you can completely ignore that part of the HTTP267specification.268269You have no idea what an HTTP method is?  Worry not, here quick270introduction in HTTP methods and why they matter:271272The HTTP method (also often called "the verb") tells the server what the273clients wants to *do* with the requested page.  The following methods are274very common:275276`GET`277    The Browser tells the server: just *get* me the information stored on278    that page and send them to me.  This is probably the most common279    method.280281`HEAD`282    The Browser tells the server: get me the information, but I am only283    interested in the *headers*, not the content of the page.  An284    application is supposed to handle that as if a `GET` request was285    received but not deliver the actual contents.  In Flask you don't have286    to deal with that at all, the underlying Werkzeug library handles that287    for you.288289`POST`290    The browser tells the server that it wants to *post* some new291    information to that URL and that the server must ensure the data is292    stored and only stored once.  This is how HTML forms are usually293    transmitting data to the server.294295`PUT`296    Similar to `POST` but the server might trigger the store procedure297    multiple times by overwriting the old values more than once.  Now you298    might be asking why this is any useful, but there are some good299    reasons to do that.  Consider the connection is lost during300    transmission, in that situation a system between the browser and the301    server might sent the request safely a second time without breaking302    things.  With `POST` that would not be possible because it must only303    be triggered once.304305`DELETE`306    Remove the information that the given location.307308Now the interesting part is that in HTML4 and XHTML1, the only methods a309form might submit to the server are `GET` and `POST`.  But with JavaScript310and future HTML standards you can use other methods as well.  Furthermore311HTTP became quite popular lately and there are more things than browsers312that are speaking HTTP.  (Your revision control system for instance might313speak HTTP)314315.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt316317Static Files318------------319320Dynamic web applications need static files as well.  That's usually where321the CSS and JavaScript files are coming from.  Ideally your web server is322configured to serve them for you, but during development Flask can do that323as well.  Just create a folder called `static` in your package or next to324your module and it will be available at `/static` on the application.325326To generate URLs to that part of the URL, use the special ``'static'`` URL327name::328329    url_for('static', filename='style.css')330331The file has to be stored on the filesystem as ``static/style.css``.332333Rendering Templates334-------------------335336Generating HTML from within Python is not fun, and actually pretty337cumbersome because you have to do the HTML escaping on your own to keep338the application secure.  Because of that Flask configures the `Jinja2339<http://jinja.pocoo.org/2/>`_ template engine for you automatically.340341To render a template you can use the :func:`~flask.render_template`342method.  All you have to do is to provide the name of the template and the343variables you want to pass to the template engine as keyword arguments.344Here's a simple example of how to render a template::345346    from flask import render_template347348    @app.route('/hello/')349    @app.route('/hello/<name>')350    def hello(name=None):351        return render_template('hello.html', name=name)352353Flask will look for templates in the `templates` folder.  So if your354application is a module, that folder is next to that module, if it's a355package it's actually inside your package:356357**Case 1**: a module::358359    /application.py360    /templates361        /hello.html362363**Case 2**: a package::364365    /application366        /__init__.py367        /templates368            /hello.html369370For templates you can use the full power of Jinja2 templates.  Head over371to the `Jinja2 Template Documentation372<http://jinja.pocoo.org/2/documentation/templates>`_ for more information.373374Here an example template:375376.. sourcecode:: html+jinja377378    <!doctype html>379    <title>Hello from Flask</title>380    {% if name %}381      <h1>Hello {{ name }}!</h1>382    {% else %}383      <h1>Hello World!</h1>384    {% endif %}385386Inside templates you also have access to the :class:`~flask.request`,387:class:`~flask.session` and :class:`~flask.g` [#]_ objects388as well as the :func:`~flask.get_flashed_messages` function.389390Templates are especially useful if inheritance is used.  If you want to391know how that works, head over to the :ref:`template-inheritance` pattern392documentation.  Basically template inheritance makes it possible to keep393certain elements on each page (like header, navigation and footer).394395Automatic escaping is enabled, so if name contains HTML it will be escaped396automatically.  If you can trust a variable and you know that it will be397safe HTML (because for example it came from a module that converts wiki398markup to HTML) you can mark it as safe by using the399:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the400template.  Head over to the Jinja 2 documentation for more examples.401402Here a basic introduction in how the :class:`~jinja2.Markup` class works:403404>>> from flask import Markup405>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'406Markup(u'<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')407>>> Markup.escape('<blink>hacker</blink>')408Markup(u'&lt;blink&gt;hacker&lt;/blink&gt;')409>>> Markup('<em>Marked up</em> &raquo; HTML').striptags()410u'Marked up \xbb HTML'411412.. [#] Unsure what that :class:`~flask.g` object is? It's something you413   can store information on yourself, check the documentation of that414   object (:class:`~flask.g`) and the :ref:`sqlite3` for more415   information.416417418Accessing Request Data419----------------------420421For web applications it's crucial to react to the data a client sent to422the server.  In Flask this information is provided by the global423:class:`~flask.request` object.  If you have some experience with Python424you might be wondering how that object can be global and how Flask425manages to still be threadsafe.  The answer are context locals:426427428.. _context-locals:429430Context Locals431``````````````432433.. admonition:: Insider Information434435   If you want to understand how that works and how you can implement436   tests with context locals, read this section, otherwise just skip it.437438Certain objects in Flask are global objects, but not just a standard439global object, but actually a proxy to an object that is local to a440specific context.  What a mouthful.  But that is actually quite easy to441understand.442443Imagine the context being the handling thread.  A request comes in and the444webserver decides to spawn a new thread (or something else, the445underlying object is capable of dealing with other concurrency systems446than threads as well).  When Flask starts its internal request handling it447figures out that the current thread is the active context and binds the448current application and the WSGI environments to that context (thread).449It does that in an intelligent way that one application can invoke another450application without breaking.451452So what does this mean to you?  Basically you can completely ignore that453this is the case unless you are unittesting or something different.  You454will notice that code that depends on a request object will suddenly break455because there is no request object.  The solution is creating a request456object yourself and binding it to the context.  The easiest solution for457unittesting is by using the :meth:`~flask.Flask.test_request_context`458context manager.  In combination with the `with` statement it will bind a459test request so that you can interact with it.  Here an example::460461    from flask import request462463    with app.test_request_context('/hello', method='POST'):464        # now you can do something with the request until the465        # end of the with block, such as basic assertions:466        assert request.path == '/hello'467        assert request.method == 'POST'468469The other possibility is passing a whole WSGI environment to the470:meth:`~flask.Flask.request_context` method::471472    from flask import request473474    with app.request_context(environ):475        assert request.method == 'POST'476477The Request Object478``````````````````479480The request object is documented in the API section and we will not cover481it here in detail (see :class:`~flask.request`), but just mention some of482the most common operations.  First of all you have to import it from the483the `flask` module::484485    from flask import request486487The current request method is available by using the488:attr:`~flask.request.method` attribute.  To access form data (data489transmitted in a `POST` or `PUT` request) you can use the490:attr:`~flask.request.form` attribute.  Here a full example of the two491attributes mentioned above::492493    @app.route('/login', methods=['POST', 'GET'])494    def login():495        error = None496        if request.method == 'POST':497            if valid_login(request.form['username'],498                           request.form['password']):499                return log_the_user_in(request.form['username'])500            else:501                error = 'Invalid username/password'502        # this is executed if the request method was GET or the503        # credentials were invalid504505What happens if the key does not exist in the `form` attribute?  In that506case a special :exc:`KeyError` is raised.  You can catch it like a507standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request508error page is shown instead.  So for many situations you don't have to509deal with that problem.510511To access parameters submitted in the URL (``?key=value``) you can use the512:attr:`~flask.request.args` attribute::513514    searchword = request.args.get('q', '')515516We recommend accessing URL parameters with `get` or by catching the517`KeyError` because users might change the URL and presenting them a 400518bad request page in that case is a bit user unfriendly.519520For a full list of methods and attributes on that object, head over to the521:class:`~flask.request` documentation.522523524File Uploads525````````````526527Obviously you can handle uploaded files with Flask just as easy.  Just528make sure not to forget to set the ``enctype="multipart/form-data"``529attribute on your HTML form, otherwise the browser will not transmit your530files at all.531532Uploaded files are stored in memory or at a temporary location on the533filesystem.  You can access those files by looking at the534:attr:`~flask.request.files` attribute on the request object.  Each535uploaded file is stored in that dictionary.  It behaves just like a536standard Python :class:`file` object, but it also has a537:meth:`~werkzeug.FileStorage.save` method that allows you to store that538file on the filesystem of the server.  Here a simple example how that539works::540541    from flask import request542543    @app.route('/upload', methods=['GET', 'POST'])544    def upload_file():545        if request.method == 'POST':546            f = request.files['the_file']547            f.save('/var/www/uploads/uploaded_file.txt')548        ...549550If you want to know how the file was named on the client before it was551uploaded to your application, you can access the552:attr:`~werkzeug.FileStorage.filename` attribute.  However please keep in553mind that this value can be forged so never ever trust that value.  If you554want to use the filename of the client to store the file on the server,555pass it through the :func:`~werkzeug.secure_filename` function that556Werkzeug provides for you::557558    from flask import request559    from werkzeug import secure_filename560561    @app.route('/upload', methods=['GET', 'POST'])562    def upload_file():563        if request.method == 'POST':564            f = request.files['the_file']565            f.save('/var/www/uploads/' + secure_filename(f.filename))566        ...567568For some better examples, checkout the :ref:`uploading-files` pattern.569570Cookies571```````572573To access cookies you can use the :attr:`~flask.request.cookies`574attribute.  Again this is a dictionary with all the cookies the client575transmits.  If you want to use sessions, do not use the cookies directly576but instead use the :ref:`sessions` in Flask that add some security on top577of cookies for you.578579580Redirects and Errors581--------------------582583To redirect a user to somewhere else you can use the584:func:`~flask.redirect` function, to abort a request early with an error585code the :func:`~flask.abort` function.  Here an example how this works::586587    from flask import abort, redirect, url_for588589    @app.route('/')590    def index():591        return redirect(url_for('login'))592593    @app.route('/login')594    def login():595        abort(401)596        this_is_never_executed()597598This is a rather pointless example because a user will be redirected from599the index to a page he cannot access (401 means access denied) but it600shows how that works.601602By default a black and white error page is shown for each error code.  If603you want to customize the error page, you can use the604:meth:`~flask.Flask.errorhandler` decorator::605606    from flask import render_template607608    @app.errorhandler(404)609    def page_not_found(error):610        return render_template('page_not_found.html'), 404611612Note the ``404`` after the :func:`~flask.render_template` call.  This613tells Flask that the status code of that page should be 404 which means614not found.  By default 200 is assumed which translates to: all went well.615616.. _sessions:617618Sessions619--------620621Besides the request object there is also a second object called622:class:`~flask.session` that allows you to store information specific to a623user from one request to the next.  This is implemented on top of cookies624for you and signs the cookies cryptographically.  What this means is that625the user could look at the contents of your cookie but not modify it,626unless he knows the secret key used for signing.627628In order to use sessions you have to set a secret key.  Here is how629sessions work::630631    from flask import session, redirect, url_for, escape632633    @app.route('/')634    def index():635        if 'username' in session:636            return 'Logged in as %s' % escape(session['username'])637        return 'You are not logged in'638639    @app.route('/login', methods=['GET', 'POST'])640    def login():641        if request.method == 'POST':642            session['username'] = request.form['username']643            return redirect(url_for('index'))644        return '''645            <form action="" method="post">646                <p><input type=text name=username>647                <p><input type=submit value=Login>648            </form>649        '''650651    @app.route('/logout')652    def logout():653        # remove the username from the session if its there654        session.pop('username', None)655656    # set the secret key.  keep this really secret:657    app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'658659The here mentioned :func:`~flask.escape` does escaping for you if you are660not using the template engine (like in this example).661662.. admonition:: How to generate good Secret Keys663664   The problem with random is that it's hard to judge what random is.  And665   a secret key should be as random as possible.  Your operating system666   has ways to generate pretty random stuff based on a cryptographic667   random generator which can be used to get such a key:668669   >>> import os670   >>> os.urandom(24)671   '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'672673   Just take that thing and copy/paste it into your code and you're done.674675Message Flashing676----------------677678Good applications and user interfaces are all about feedback.  If the user679does not get enough feedback he will probably end up hating the680application.  Flask provides a really simple way to give feedback to a681user with the flashing system.  The flashing system basically makes it682possible to record a message at the end of a request and access it next683request and only next request.  This is usually combined with a layout684template that does this.685686To flash a message use the :func:`~flask.flash` method, to get hold of the687messages you can use :func:`~flask.get_flashed_messages` which is also688available in the templates.  Check out the :ref:`message-flashing-pattern`689for a full example.690691Logging692-------693694.. versionadded:: 0.3695696Sometimes you might be in the situation where you deal with data that697should be correct, but actually is not.  For example you have some client698side code that sends an HTTP request to the server, and it's obviously699malformed.  This might be caused by a user tempering with the data, or the700client code failed.  Most the time, it's okay to reply with ``400 Bad701Request`` in that situation, but other times it is not and the code has to702continue working.703704Yet you want to log that something fishy happened.  This is where loggers705come in handy.  As of Flask 0.3 a logger is preconfigured for you to use.706707Here are some example log calls::708709    app.logger.debug('A value for debugging')710    app.logger.warning('A warning occurred (%d apples)', 42)711    app.logger.error('An error occurred')712713The attached :attr:`~flask.Flask.logger` is a standard logging714:class:`~logging.Logger`, so head over to the official stdlib715documentation for more information.