Skip to content
Myr

quickstart.rst

This file

Path

docs/quickstart.rst

750 lines · 27.2 KiB

Last changed by

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

History of this file

Take it

1.. _quickstart:23Quickstart4==========56Eager to get started?  This page gives a good introduction in how to get7started 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.  The first argument is the name of42   the application's module.  If you are using a single module (like here)43   you should use `__name__` because depending on if it's started as44   application or imported as module the name will be different45   (``'__main__'`` versus the actual import name).  For more information46   on that, have a look at the :class:`~flask.Flask` documentation.472. Next we create an instance of it.  We pass it the name of the module /48   package.  This is needed so that Flask knows where it should look for49   templates, static files and so on.503. Then we use the :meth:`~flask.Flask.route` decorator to tell Flask51   what URL should trigger our function.524. The function then has a name which is also used to generate URLs to53   that particular function, and returns the message we want to display in54   the user's browser.555. Finally we use the :meth:`~flask.Flask.run` function to run the56   local server with our application.  The ``if __name__ == '__main__':``57   makes sure the server only runs if the script is executed directly from58   the Python interpreter and not used as imported module.5960To stop the server, hit control-C.6162.. _public-server:6364.. admonition:: Externally Visible Server6566   If you run the server you will notice that the server is only available67   from your own computer, not from any other in the network.  This is the68   default because in debugging mode a user of the application can execute69   arbitrary Python code on your computer.  If you have `debug` disabled70   or trust the users on your network, you can make the server publicly71   available.7273   Just change the call of the :meth:`~flask.Flask.run` method to look74   like this::7576       app.run(host='0.0.0.0')7778   This tells your operating system to listen on a public IP.798081Debug Mode82----------8384The :meth:`~flask.Flask.run` method is nice to start a local85development server, but you would have to restart it manually after each86change you do to code.  That is not very nice and Flask can do better.  If87you enable the debug support the server will reload itself on code changes88and also provide you with a helpful debugger if things go wrong.8990There are two ways to enable debugging.  Either set that flag on the91application object::9293    app.debug = True94    app.run()9596Or pass it to run::9798    app.run(debug=True)99100Both will have exactly the same effect.101102.. admonition:: Attention103104   Even though the interactive debugger does not work in forking environments105   (which makes it nearly impossible to use on production servers), it still106   allows the execution of arbitrary code. That makes it a major security107   risk and therefore it **must never be used on production machines**.108109Screenshot of the debugger in action:110111.. image:: _static/debugger.png112   :align: center113   :class: screenshot114   :alt: screenshot of debugger in action115116.. admonition:: Working With Other Debuggers117118   Debuggers interfere with each other.  If you are using another debugger119   (e.g. PyDev or IntelliJ), you may need to set ``app.debug = False``.120121122Routing123-------124125Modern web applications have beautiful URLs.  This helps people remember126the URLs which is especially handy for applications that are used from127mobile devices with slower network connections.  If the user can directly128go to the desired page without having to hit the index page it is more129likely he will like the page and come back next time.130131As you have seen above, the :meth:`~flask.Flask.route` decorator is used132to bind a function to a URL.  Here are some basic examples::133134    @app.route('/')135    def index():136        return 'Index Page'137138    @app.route('/hello')139    def hello():140        return 'Hello World'141142But there is more to it!  You can make certain parts of the URL dynamic143and attach multiple rules to a function.144145Variable Rules146``````````````147148To add variable parts to a URL you can mark these special sections as149``<variable_name>``.  Such a part is then passed as keyword argument to150your function.  Optionally a converter can be specified by specifying a151rule with ``<converter:variable_name>``.  Here are some nice examples::152153    @app.route('/user/<username>')154    def show_user_profile(username):155        # show the user profile for that user156        pass157158    @app.route('/post/<int:post_id>')159    def show_post(post_id):160        # show the post with the given id, the id is an integer161        pass162163The following converters exist:164165=========== ===========================================166`int`       accepts integers167`float`     like `int` but for floating point values168`path`      like the default but also accepts slashes169=========== ===========================================170171.. admonition:: Unique URLs / Redirection Behaviour172173   Flask's URL rules are based on Werkzeug's routing module.  The idea174   behind that module is to ensure nice looking and also unique URLs based175   on behaviour Apache and earlier servers coined.176177   Take these two rules::178179        @app.route('/projects/')180        def projects():181            pass182183        @app.route('/about')184        def about():185            pass186187   They look rather similar, the difference is the trailing slash in the188   URL *definition*.  In the first case, the canonical URL for the189   `projects` endpoint has a trailing slash.  It's similar to a folder in190   that sense.  Accessing it without a trailing slash will cause Flask to191   redirect to the canonical URL with the trailing slash.192193   However in the second case the URL is defined without a slash so it194   behaves similar to a file and accessing the URL with a trailing slash195   will be a 404 error.196197   Why is this?  This allows relative URLs to continue working if users198   access the page when they forget a trailing slash.  This behaviour is199   also consistent with how Apache and other servers work.  Also, the URLs200   will stay unique which helps search engines not indexing the same page201   twice.202203204.. _url-building:205206URL Building207````````````208209If it can match URLs, can it also generate them?  Of course it can.  To210build a URL to a specific function you can use the :func:`~flask.url_for`211function.  It accepts the name of the function as first argument and a212number of keyword arguments, each corresponding to the variable part of213the URL rule.  Unknown variable parts are appended to the URL as query214parameter.  Here are some examples:215216>>> from flask import Flask, url_for217>>> app = Flask(__name__)218>>> @app.route('/')219... def index(): pass220...221>>> @app.route('/login')222... def login(): pass223...224>>> @app.route('/user/<username>')225... def profile(username): pass226...227>>> with app.test_request_context():228...  print url_for('index')229...  print url_for('login')230...  print url_for('login', next='/')231...  print url_for('profile', username='John Doe')232...233/234/login235/login?next=/236/user/John%20Doe237238(This also uses the :meth:`~flask.Flask.test_request_context` method239explained below.  It basically tells Flask to think we are handling a240request even though we are not, we are in an interactive Python shell.241Have a look at the explanation below. :ref:`context-locals`).242243Why would you want to build URLs instead of hardcoding them in your244templates?  There are three good reasons for this:2452461. reversing is often more descriptive than hardcoding the URLs.  Also and247   more importantly you can change URLs in one go without having to change248   the URLs all over the place.2492. URL building will handle escaping of special characters and Unicode250   data transparently for you, you don't have to deal with that.2513. If your application is placed outside the URL root (so say in252   ``/myapplication`` instead of ``/``), :func:`~flask.url_for` will253   handle that properly for you.254255256HTTP Methods257````````````258259HTTP (the protocol web applications are speaking) knows different methods260to access URLs.  By default a route only answers to `GET` requests, but261that can be changed by providing the `methods` argument to the262:meth:`~flask.Flask.route` decorator.  Here are some examples::263264    @app.route('/login', methods=['GET', 'POST'])265    def login():266        if request.method == 'POST':267            do_the_login()268        else:269            show_the_login_form()270271If `GET` is present, `HEAD` will be added automatically for you.  You272don't have to deal with that.  It will also make sure that `HEAD` requests273are handled like the `HTTP RFC`_ (the document describing the HTTP274protocol) demands, so you can completely ignore that part of the HTTP275specification.  Likewise as of Flask 0.6, `OPTIONS` is implemented for you276as well automatically.277278You have no idea what an HTTP method is?  Worry not, here is a quick279introduction to HTTP methods and why they matter:280281The HTTP method (also often called "the verb") tells the server what the282clients wants to *do* with the requested page.  The following methods are283very common:284285`GET`286    The browser tells the server to just *get* the information stored on287    that page and send it.  This is probably the most common method.288289`HEAD`290    The browser tells the server to get the information, but it is only291    interested in the *headers*, not the content of the page.  An292    application is supposed to handle that as if a `GET` request was293    received but to not deliver the actual content.  In Flask you don't294    have to deal with that at all, the underlying Werkzeug library handles295    that for you.296297`POST`298    The browser tells the server that it wants to *post* some new299    information to that URL and that the server must ensure the data is300    stored and only stored once.  This is how HTML forms are usually301    transmitting data to the server.302303`PUT`304    Similar to `POST` but the server might trigger the store procedure305    multiple times by overwriting the old values more than once.  Now you306    might be asking why is this useful, but there are some good reasons307    to do it this way.  Consider that the connection gets lost during308    transmission: in this situation a system between the browser and the309    server might receive the request safely a second time without breaking310    things.  With `POST` that would not be possible because it must only311    be triggered once.312313`DELETE`314    Remove the information at the given location.315316`OPTIONS`317    Provides a quick way for a client to figure out which methods are318    supported by this URL.  Starting with Flask 0.6, this is implemented319    for you automatically.320321Now the interesting part is that in HTML4 and XHTML1, the only methods a322form can submit to the server are `GET` and `POST`.  But with JavaScript323and future HTML standards you can use the other methods as well.  Furthermore324HTTP has become quite popular lately and browsers are no longer the only325clients that are using HTTP. For instance, many revision control system326use it.327328.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt329330Static Files331------------332333Dynamic web applications need static files as well.  That's usually where334the CSS and JavaScript files are coming from.  Ideally your web server is335configured to serve them for you, but during development Flask can do that336as well.  Just create a folder called `static` in your package or next to337your module and it will be available at `/static` on the application.338339To generate URLs to that part of the URL, use the special ``'static'`` URL340name::341342    url_for('static', filename='style.css')343344The file has to be stored on the filesystem as ``static/style.css``.345346Rendering Templates347-------------------348349Generating HTML from within Python is not fun, and actually pretty350cumbersome because you have to do the HTML escaping on your own to keep351the application secure.  Because of that Flask configures the `Jinja2352<http://jinja.pocoo.org/2/>`_ template engine for you automatically.353354To render a template you can use the :func:`~flask.render_template`355method.  All you have to do is to provide the name of the template and the356variables you want to pass to the template engine as keyword arguments.357Here's a simple example of how to render a template::358359    from flask import render_template360361    @app.route('/hello/')362    @app.route('/hello/<name>')363    def hello(name=None):364        return render_template('hello.html', name=name)365366Flask will look for templates in the `templates` folder.  So if your367application is a module, that folder is next to that module, if it's a368package it's actually inside your package:369370**Case 1**: a module::371372    /application.py373    /templates374        /hello.html375376**Case 2**: a package::377378    /application379        /__init__.py380        /templates381            /hello.html382383For templates you can use the full power of Jinja2 templates.  Head over384to the :ref:`templating` section of the documentation or the official385`Jinja2 Template Documentation386<http://jinja.pocoo.org/2/documentation/templates>`_ for more information.387388Here is an example template:389390.. sourcecode:: html+jinja391392    <!doctype html>393    <title>Hello from Flask</title>394    {% if name %}395      <h1>Hello {{ name }}!</h1>396    {% else %}397      <h1>Hello World!</h1>398    {% endif %}399400Inside templates you also have access to the :class:`~flask.request`,401:class:`~flask.session` and :class:`~flask.g` [#]_ objects402as well as the :func:`~flask.get_flashed_messages` function.403404Templates are especially useful if inheritance is used.  If you want to405know how that works, head over to the :ref:`template-inheritance` pattern406documentation.  Basically template inheritance makes it possible to keep407certain elements on each page (like header, navigation and footer).408409Automatic escaping is enabled, so if name contains HTML it will be escaped410automatically.  If you can trust a variable and you know that it will be411safe HTML (because for example it came from a module that converts wiki412markup to HTML) you can mark it as safe by using the413:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the414template.  Head over to the Jinja 2 documentation for more examples.415416Here is a basic introduction to how the :class:`~jinja2.Markup` class works:417418>>> from flask import Markup419>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'420Markup(u'<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')421>>> Markup.escape('<blink>hacker</blink>')422Markup(u'&lt;blink&gt;hacker&lt;/blink&gt;')423>>> Markup('<em>Marked up</em> &raquo; HTML').striptags()424u'Marked up \xbb HTML'425426.. versionchanged:: 0.5427428   Autoescaping is no longer enabled for all templates.  The following429   extensions for templates trigger autoescaping: ``.html``, ``.htm``,430   ``.xml``, ``.xhtml``.  Templates loaded from a string will have431   autoescaping disabled.432433.. [#] Unsure what that :class:`~flask.g` object is? It's something in which434   you can store information for your own needs, check the documentation of435   that object (:class:`~flask.g`) and the :ref:`sqlite3` for more436   information.437438439Accessing Request Data440----------------------441442For web applications it's crucial to react to the data a client sent to443the server.  In Flask this information is provided by the global444:class:`~flask.request` object.  If you have some experience with Python445you might be wondering how that object can be global and how Flask446manages to still be threadsafe.  The answer are context locals:447448449.. _context-locals:450451Context Locals452``````````````453454.. admonition:: Insider Information455456   If you want to understand how that works and how you can implement457   tests with context locals, read this section, otherwise just skip it.458459Certain objects in Flask are global objects, but not of the usual kind.460These objects are actually proxies to objects that are local to a specific461context.  What a mouthful.  But that is actually quite easy to understand.462463Imagine the context being the handling thread.  A request comes in and the464webserver decides to spawn a new thread (or something else, the465underlying object is capable of dealing with other concurrency systems466than threads as well).  When Flask starts its internal request handling it467figures out that the current thread is the active context and binds the468current application and the WSGI environments to that context (thread).469It does that in an intelligent way that one application can invoke another470application without breaking.471472So what does this mean to you?  Basically you can completely ignore that473this is the case unless you are doing something like unittesting.  You474will notice that code that depends on a request object will suddenly break475because there is no request object.  The solution is creating a request476object yourself and binding it to the context.  The easiest solution for477unittesting is by using the :meth:`~flask.Flask.test_request_context`478context manager.  In combination with the `with` statement it will bind a479test request so that you can interact with it.  Here is an example::480481    from flask import request482483    with app.test_request_context('/hello', method='POST'):484        # now you can do something with the request until the485        # end of the with block, such as basic assertions:486        assert request.path == '/hello'487        assert request.method == 'POST'488489The other possibility is passing a whole WSGI environment to the490:meth:`~flask.Flask.request_context` method::491492    from flask import request493494    with app.request_context(environ):495        assert request.method == 'POST'496497The Request Object498``````````````````499500The request object is documented in the API section and we will not cover501it here in detail (see :class:`~flask.request`). Here is a broad overview of502some of the most common operations.  First of all you have to import it from503the `flask` module::504505    from flask import request506507The current request method is available by using the508:attr:`~flask.request.method` attribute.  To access form data (data509transmitted in a `POST` or `PUT` request) you can use the510:attr:`~flask.request.form` attribute.  Here is a full example of the two511attributes mentioned above::512513    @app.route('/login', methods=['POST', 'GET'])514    def login():515        error = None516        if request.method == 'POST':517            if valid_login(request.form['username'],518                           request.form['password']):519                return log_the_user_in(request.form['username'])520            else:521                error = 'Invalid username/password'522        # this is executed if the request method was GET or the523        # credentials were invalid524525What happens if the key does not exist in the `form` attribute?  In that526case a special :exc:`KeyError` is raised.  You can catch it like a527standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request528error page is shown instead.  So for many situations you don't have to529deal with that problem.530531To access parameters submitted in the URL (``?key=value``) you can use the532:attr:`~flask.request.args` attribute::533534    searchword = request.args.get('q', '')535536We recommend accessing URL parameters with `get` or by catching the537`KeyError` because users might change the URL and presenting them a 400538bad request page in that case is not user friendly.539540For a full list of methods and attributes of the request object, head over541to the :class:`~flask.request` documentation.542543544File Uploads545````````````546547You can handle uploaded files with Flask easily.  Just make sure not to548forget to set the ``enctype="multipart/form-data"`` attribute on your HTML549form, otherwise the browser will not transmit your files at all.550551Uploaded files are stored in memory or at a temporary location on the552filesystem.  You can access those files by looking at the553:attr:`~flask.request.files` attribute on the request object.  Each554uploaded file is stored in that dictionary.  It behaves just like a555standard Python :class:`file` object, but it also has a556:meth:`~werkzeug.datastructures.FileStorage.save` method that allows you to store that557file on the filesystem of the server.  Here is a simple example showing how558that works::559560    from flask import request561562    @app.route('/upload', methods=['GET', 'POST'])563    def upload_file():564        if request.method == 'POST':565            f = request.files['the_file']566            f.save('/var/www/uploads/uploaded_file.txt')567        ...568569If you want to know how the file was named on the client before it was570uploaded to your application, you can access the571:attr:`~werkzeug.datastructures.FileStorage.filename` attribute.  However please keep in572mind that this value can be forged so never ever trust that value.  If you573want to use the filename of the client to store the file on the server,574pass it through the :func:`~werkzeug.utils.secure_filename` function that575Werkzeug provides for you::576577    from flask import request578    from werkzeug import secure_filename579580    @app.route('/upload', methods=['GET', 'POST'])581    def upload_file():582        if request.method == 'POST':583            f = request.files['the_file']584            f.save('/var/www/uploads/' + secure_filename(f.filename))585        ...586587For some better examples, checkout the :ref:`uploading-files` pattern.588589Cookies590```````591592To access cookies you can use the :attr:`~flask.request.cookies`593attribute.  Again this is a dictionary with all the cookies the client594transmits.  If you want to use sessions, do not use the cookies directly595but instead use the :ref:`sessions` in Flask that add some security on top596of cookies for you.597598599Redirects and Errors600--------------------601602To redirect a user to somewhere else you can use the603:func:`~flask.redirect` function. To abort a request early with an error604code use the :func:`~flask.abort` function.  Here an example how this works::605606    from flask import abort, redirect, url_for607608    @app.route('/')609    def index():610        return redirect(url_for('login'))611612    @app.route('/login')613    def login():614        abort(401)615        this_is_never_executed()616617This is a rather pointless example because a user will be redirected from618the index to a page he cannot access (401 means access denied) but it619shows how that works.620621By default a black and white error page is shown for each error code.  If622you want to customize the error page, you can use the623:meth:`~flask.Flask.errorhandler` decorator::624625    from flask import render_template626627    @app.errorhandler(404)628    def page_not_found(error):629        return render_template('page_not_found.html'), 404630631Note the ``404`` after the :func:`~flask.render_template` call.  This632tells Flask that the status code of that page should be 404 which means633not found.  By default 200 is assumed which translates to: all went well.634635.. _sessions:636637Sessions638--------639640Besides the request object there is also a second object called641:class:`~flask.session` that allows you to store information specific to a642user from one request to the next.  This is implemented on top of cookies643for you and signs the cookies cryptographically.  What this means is that644the user could look at the contents of your cookie but not modify it,645unless he knows the secret key used for signing.646647In order to use sessions you have to set a secret key.  Here is how648sessions work::649650    from flask import Flask, session, redirect, url_for, escape, request651652    app = Flask(__name__)653654    @app.route('/')655    def index():656        if 'username' in session:657            return 'Logged in as %s' % escape(session['username'])658        return 'You are not logged in'659660    @app.route('/login', methods=['GET', 'POST'])661    def login():662        if request.method == 'POST':663            session['username'] = request.form['username']664            return redirect(url_for('index'))665        return '''666            <form action="" method="post">667                <p><input type=text name=username>668                <p><input type=submit value=Login>669            </form>670        '''671672    @app.route('/logout')673    def logout():674        # remove the username from the session if its there675        session.pop('username', None)676        return redirect(url_for('index'))677678    # set the secret key.  keep this really secret:679    app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'680681The here mentioned :func:`~flask.escape` does escaping for you if you are682not using the template engine (like in this example).683684.. admonition:: How to generate good secret keys685686   The problem with random is that it's hard to judge what random is.  And687   a secret key should be as random as possible.  Your operating system688   has ways to generate pretty random stuff based on a cryptographic689   random generator which can be used to get such a key:690691   >>> import os692   >>> os.urandom(24)693   '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'694695   Just take that thing and copy/paste it into your code and you're done.696697Message Flashing698----------------699700Good applications and user interfaces are all about feedback.  If the user701does not get enough feedback he will probably end up hating the702application.  Flask provides a really simple way to give feedback to a703user with the flashing system.  The flashing system basically makes it704possible to record a message at the end of a request and access it next705request and only next request.  This is usually combined with a layout706template that does this.707708To flash a message use the :func:`~flask.flash` method, to get hold of the709messages you can use :func:`~flask.get_flashed_messages` which is also710available in the templates.  Check out the :ref:`message-flashing-pattern`711for a full example.712713Logging714-------715716.. versionadded:: 0.3717718Sometimes you might be in a situation where you deal with data that719should be correct, but actually is not.  For example you may have some client720side code that sends an HTTP request to the server but it's obviously721malformed.  This might be caused by a user tempering with the data, or the722client code failing.  Most of the time, it's okay to reply with ``400 Bad723Request`` in that situation, but sometimes that won't do and the code has724to continue working.725726You may still want to log that something fishy happened.  This is where727loggers come in handy.  As of Flask 0.3 a logger is preconfigured for you728to use.729730Here are some example log calls::731732    app.logger.debug('A value for debugging')733    app.logger.warning('A warning occurred (%d apples)', 42)734    app.logger.error('An error occurred')735736The attached :attr:`~flask.Flask.logger` is a standard logging737:class:`~logging.Logger`, so head over to the official `logging738documentation <http://docs.python.org/library/logging.html>`_ for more739information.740741Hooking in WSGI Middlewares742---------------------------743744If you want to add a WSGI middleware to your application you can wrap the745internal WSGI application.  For example if you want to use one of the746middlewares from the Werkzeug package to work around bugs in lighttpd, you747can do it like this::748749    from werkzeug.contrib.fixers import LighttpdCGIRootFix750    app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)