Skip to content
Myr

quickstart.rst

This file

Path

docs/quickstart.rst

730 lines · 26.2 KiB

Last changed by

Started working on refactoring Jinja integrationArmin Ronacherbefore adoption7599046

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.  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----------8384Now that :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   The interactive debugger however does not work in forking environments105   which makes it nearly impossible to use on production servers but the106   debugger still allows the execution of arbitrary code which makes it a107   major security risk and **must never be used on production machines**108   because of that.109110Screenshot of the debugger in action:111112.. image:: _static/debugger.png113   :align: center114   :class: screenshot115   :alt: screenshot of debugger in action116117118Routing119-------120121As you have seen above, the :meth:`~flask.Flask.route` decorator is used122to bind a function to a URL.  But there is more to it!  You can make123certain parts of the URL dynamic and attach multiple rules to a function.124125Here some examples::126127    @app.route('/')128    def index():129        return 'Index Page'130131    @app.route('/hello')132    def hello():133        return 'Hello World'134135136Variable Rules137``````````````138139Modern web applications have beautiful URLs.  This helps people remember140the URLs which is especially handy for applications that are used from141mobile devices with slower network connections.  If the user can directly142go to the desired page without having to hit the index page it is more143likely he will like the page and come back next time.144145To add variable parts to a URL you can mark these special sections as146``<variable_name>``.  Such a part is then passed as keyword argument to147your function.  Optionally a converter can be specified by specifying a148rule with ``<converter:variable_name>``.  Here some nice examples::149150    @app.route('/user/<username>')151    def show_user_profile(username):152        # show the user profile for that user153        pass154155    @app.route('/post/<int:post_id>')156    def show_post(post_id):157        # show the post with the given id, the id is an integer158        pass159160The following converters exist:161162=========== ===========================================163`int`       accepts integers164`float`     like `int` but for floating point values165`path`      like the default but also accepts slashes166=========== ===========================================167168.. admonition:: Unique URLs / Redirection Behaviour169170   Flask's URL rules are based on Werkzeug's routing module.  The idea171   behind that module is to ensure nice looking and also unique URLs based172   on behaviour Apache and earlier servers coined.173174   Take these two rules::175176        @app.route('/projects/')177        def projects():178            pass179180        @app.route('/about')181        def about():182            pass183184   They look rather similar, the difference is the trailing slash in the185   URL *definition*.  In the first case, the canonical URL for the186   `projects` endpoint has a trailing slash.  It's similar to a folder in187   that sense.  Accessing it without a trailing slash will cause Flask to188   redirect to the canonical URL with the trailing slash.189190   However in the second case the URL is defined without a slash so it191   behaves similar to a file and accessing the URL with a trailing slash192   will be a 404 error.193194   Why is this?  This allows relative URLs to continue working if users195   access the page when they forget a trailing slash.  This behaviour is196   also consistent with how Apache and other servers work.  Also, the URLs197   will stay unique which helps search engines not indexing the same page198   twice.199200201.. _url-building:202203URL Building204````````````205206If it can match URLs, can it also generate them?  Of course you can.  To207build a URL to a specific function you can use the :func:`~flask.url_for`208function.  It accepts the name of the function as first argument and a209number of keyword arguments, each corresponding to the variable part of210the URL rule.  Unknown variable parts are appended to the URL as query211parameter.  Here some examples:212213>>> from flask import Flask, url_for214>>> app = Flask(__name__)215>>> @app.route('/')216... def index(): pass217...218>>> @app.route('/login')219... def login(): pass220...221>>> @app.route('/user/<username>')222... def profile(username): pass223...224>>> with app.test_request_context():225...  print url_for('index')226...  print url_for('login')227...  print url_for('login', next='/')228...  print url_for('profile', username='John Doe')229...230/231/login232/login?next=/233/user/John%20Doe234235(This also uses the :meth:`~flask.Flask.test_request_context` method236explained below.  It basically tells flask to think we are handling a237request even though we are not, we are in an interactive Python shell.238Have a look at the explanation below. :ref:`context-locals`).239240Why would you want to build URLs instead of hardcoding them in your241templates?  There are three good reasons for this:2422431. reversing is often more descriptive than hardcoding the URLs.  Also and244   more importantly you can change URLs in one go without having to change245   the URLs all over the place.2462. URL building will handle escaping of special characters and Unicode247   data transparently for you, you don't have to deal with that.2483. If your application is placed outside the URL root (so say in249   ``/myapplication`` instead of ``/``), :func:`~flask.url_for` will250   handle that properly for you.251252253HTTP Methods254````````````255256HTTP (the protocol web applications are speaking) knows different methods257to access URLs.  By default a route only answers to `GET` requests, but258that can be changed by providing the `methods` argument to the259:meth:`~flask.Flask.route` decorator.  Here some examples::260261    @app.route('/login', methods=['GET', 'POST'])262    def login():263        if request.method == 'POST':264            do_the_login()265        else:266            show_the_login_form()267268If `GET` is present, `HEAD` will be added automatically for you.  You269don't have to deal with that.  It will also make sure that `HEAD` requests270are handled like the `HTTP RFC`_ (the document describing the HTTP271protocol) demands, so you can completely ignore that part of the HTTP272specification.273274You have no idea what an HTTP method is?  Worry not, here quick275introduction in HTTP methods and why they matter:276277The HTTP method (also often called "the verb") tells the server what the278clients wants to *do* with the requested page.  The following methods are279very common:280281`GET`282    The Browser tells the server: just *get* me the information stored on283    that page and send them to me.  This is probably the most common284    method.285286`HEAD`287    The Browser tells the server: get me the information, but I am only288    interested in the *headers*, not the content of the page.  An289    application is supposed to handle that as if a `GET` request was290    received but not deliver the actual contents.  In Flask you don't have291    to deal with that at all, the underlying Werkzeug library handles that292    for you.293294`POST`295    The browser tells the server that it wants to *post* some new296    information to that URL and that the server must ensure the data is297    stored and only stored once.  This is how HTML forms are usually298    transmitting data to the server.299300`PUT`301    Similar to `POST` but the server might trigger the store procedure302    multiple times by overwriting the old values more than once.  Now you303    might be asking why this is any useful, but there are some good304    reasons to do that.  Consider the connection is lost during305    transmission, in that situation a system between the browser and the306    server might sent the request safely a second time without breaking307    things.  With `POST` that would not be possible because it must only308    be triggered once.309310`DELETE`311    Remove the information that the given location.312313Now the interesting part is that in HTML4 and XHTML1, the only methods a314form might submit to the server are `GET` and `POST`.  But with JavaScript315and future HTML standards you can use other methods as well.  Furthermore316HTTP became quite popular lately and there are more things than browsers317that are speaking HTTP.  (Your revision control system for instance might318speak HTTP)319320.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt321322Static Files323------------324325Dynamic web applications need static files as well.  That's usually where326the CSS and JavaScript files are coming from.  Ideally your web server is327configured to serve them for you, but during development Flask can do that328as well.  Just create a folder called `static` in your package or next to329your module and it will be available at `/static` on the application.330331To generate URLs to that part of the URL, use the special ``'static'`` URL332name::333334    url_for('static', filename='style.css')335336The file has to be stored on the filesystem as ``static/style.css``.337338Rendering Templates339-------------------340341Generating HTML from within Python is not fun, and actually pretty342cumbersome because you have to do the HTML escaping on your own to keep343the application secure.  Because of that Flask configures the `Jinja2344<http://jinja.pocoo.org/2/>`_ template engine for you automatically.345346To render a template you can use the :func:`~flask.render_template`347method.  All you have to do is to provide the name of the template and the348variables you want to pass to the template engine as keyword arguments.349Here's a simple example of how to render a template::350351    from flask import render_template352353    @app.route('/hello/')354    @app.route('/hello/<name>')355    def hello(name=None):356        return render_template('hello.html', name=name)357358Flask will look for templates in the `templates` folder.  So if your359application is a module, that folder is next to that module, if it's a360package it's actually inside your package:361362**Case 1**: a module::363364    /application.py365    /templates366        /hello.html367368**Case 2**: a package::369370    /application371        /__init__.py372        /templates373            /hello.html374375For templates you can use the full power of Jinja2 templates.  Head over376to the `Jinja2 Template Documentation377<http://jinja.pocoo.org/2/documentation/templates>`_ for more information.378379Here an example template:380381.. sourcecode:: html+jinja382383    <!doctype html>384    <title>Hello from Flask</title>385    {% if name %}386      <h1>Hello {{ name }}!</h1>387    {% else %}388      <h1>Hello World!</h1>389    {% endif %}390391Inside templates you also have access to the :class:`~flask.request`,392:class:`~flask.session` and :class:`~flask.g` [#]_ objects393as well as the :func:`~flask.get_flashed_messages` function.394395Templates are especially useful if inheritance is used.  If you want to396know how that works, head over to the :ref:`template-inheritance` pattern397documentation.  Basically template inheritance makes it possible to keep398certain elements on each page (like header, navigation and footer).399400Automatic escaping is enabled, so if name contains HTML it will be escaped401automatically.  If you can trust a variable and you know that it will be402safe HTML (because for example it came from a module that converts wiki403markup to HTML) you can mark it as safe by using the404:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the405template.  Head over to the Jinja 2 documentation for more examples.406407Here a basic introduction in how the :class:`~jinja2.Markup` class works:408409>>> from flask import Markup410>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'411Markup(u'<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')412>>> Markup.escape('<blink>hacker</blink>')413Markup(u'&lt;blink&gt;hacker&lt;/blink&gt;')414>>> Markup('<em>Marked up</em> &raquo; HTML').striptags()415u'Marked up \xbb HTML'416417.. versionchanged:: 0.5418419   Autoescaping is no longer enabled for all templates.  The following420   extensions for templates trigger autoescaping: ``.html``, ``.htm``,421   ``.xml``, ``.xhtml``.  Templates loaded from string will have422   autoescaping disabled.423424.. [#] Unsure what that :class:`~flask.g` object is? It's something you425   can store information on yourself, check the documentation of that426   object (:class:`~flask.g`) and the :ref:`sqlite3` for more427   information.428429430Accessing Request Data431----------------------432433For web applications it's crucial to react to the data a client sent to434the server.  In Flask this information is provided by the global435:class:`~flask.request` object.  If you have some experience with Python436you might be wondering how that object can be global and how Flask437manages to still be threadsafe.  The answer are context locals:438439440.. _context-locals:441442Context Locals443``````````````444445.. admonition:: Insider Information446447   If you want to understand how that works and how you can implement448   tests with context locals, read this section, otherwise just skip it.449450Certain objects in Flask are global objects, but not just a standard451global object, but actually a proxy to an object that is local to a452specific context.  What a mouthful.  But that is actually quite easy to453understand.454455Imagine the context being the handling thread.  A request comes in and the456webserver decides to spawn a new thread (or something else, the457underlying object is capable of dealing with other concurrency systems458than threads as well).  When Flask starts its internal request handling it459figures out that the current thread is the active context and binds the460current application and the WSGI environments to that context (thread).461It does that in an intelligent way that one application can invoke another462application without breaking.463464So what does this mean to you?  Basically you can completely ignore that465this is the case unless you are unittesting or something different.  You466will notice that code that depends on a request object will suddenly break467because there is no request object.  The solution is creating a request468object yourself and binding it to the context.  The easiest solution for469unittesting is by using the :meth:`~flask.Flask.test_request_context`470context manager.  In combination with the `with` statement it will bind a471test request so that you can interact with it.  Here an example::472473    from flask import request474475    with app.test_request_context('/hello', method='POST'):476        # now you can do something with the request until the477        # end of the with block, such as basic assertions:478        assert request.path == '/hello'479        assert request.method == 'POST'480481The other possibility is passing a whole WSGI environment to the482:meth:`~flask.Flask.request_context` method::483484    from flask import request485486    with app.request_context(environ):487        assert request.method == 'POST'488489The Request Object490``````````````````491492The request object is documented in the API section and we will not cover493it here in detail (see :class:`~flask.request`), but just mention some of494the most common operations.  First of all you have to import it from the495the `flask` module::496497    from flask import request498499The current request method is available by using the500:attr:`~flask.request.method` attribute.  To access form data (data501transmitted in a `POST` or `PUT` request) you can use the502:attr:`~flask.request.form` attribute.  Here a full example of the two503attributes mentioned above::504505    @app.route('/login', methods=['POST', 'GET'])506    def login():507        error = None508        if request.method == 'POST':509            if valid_login(request.form['username'],510                           request.form['password']):511                return log_the_user_in(request.form['username'])512            else:513                error = 'Invalid username/password'514        # this is executed if the request method was GET or the515        # credentials were invalid516517What happens if the key does not exist in the `form` attribute?  In that518case a special :exc:`KeyError` is raised.  You can catch it like a519standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request520error page is shown instead.  So for many situations you don't have to521deal with that problem.522523To access parameters submitted in the URL (``?key=value``) you can use the524:attr:`~flask.request.args` attribute::525526    searchword = request.args.get('q', '')527528We recommend accessing URL parameters with `get` or by catching the529`KeyError` because users might change the URL and presenting them a 400530bad request page in that case is a bit user unfriendly.531532For a full list of methods and attributes on that object, head over to the533:class:`~flask.request` documentation.534535536File Uploads537````````````538539Obviously you can handle uploaded files with Flask just as easy.  Just540make sure not to forget to set the ``enctype="multipart/form-data"``541attribute on your HTML form, otherwise the browser will not transmit your542files at all.543544Uploaded files are stored in memory or at a temporary location on the545filesystem.  You can access those files by looking at the546:attr:`~flask.request.files` attribute on the request object.  Each547uploaded file is stored in that dictionary.  It behaves just like a548standard Python :class:`file` object, but it also has a549:meth:`~werkzeug.FileStorage.save` method that allows you to store that550file on the filesystem of the server.  Here a simple example how that551works::552553    from flask import request554555    @app.route('/upload', methods=['GET', 'POST'])556    def upload_file():557        if request.method == 'POST':558            f = request.files['the_file']559            f.save('/var/www/uploads/uploaded_file.txt')560        ...561562If you want to know how the file was named on the client before it was563uploaded to your application, you can access the564:attr:`~werkzeug.FileStorage.filename` attribute.  However please keep in565mind that this value can be forged so never ever trust that value.  If you566want to use the filename of the client to store the file on the server,567pass it through the :func:`~werkzeug.secure_filename` function that568Werkzeug provides for you::569570    from flask import request571    from werkzeug import secure_filename572573    @app.route('/upload', methods=['GET', 'POST'])574    def upload_file():575        if request.method == 'POST':576            f = request.files['the_file']577            f.save('/var/www/uploads/' + secure_filename(f.filename))578        ...579580For some better examples, checkout the :ref:`uploading-files` pattern.581582Cookies583```````584585To access cookies you can use the :attr:`~flask.request.cookies`586attribute.  Again this is a dictionary with all the cookies the client587transmits.  If you want to use sessions, do not use the cookies directly588but instead use the :ref:`sessions` in Flask that add some security on top589of cookies for you.590591592Redirects and Errors593--------------------594595To redirect a user to somewhere else you can use the596:func:`~flask.redirect` function, to abort a request early with an error597code the :func:`~flask.abort` function.  Here an example how this works::598599    from flask import abort, redirect, url_for600601    @app.route('/')602    def index():603        return redirect(url_for('login'))604605    @app.route('/login')606    def login():607        abort(401)608        this_is_never_executed()609610This is a rather pointless example because a user will be redirected from611the index to a page he cannot access (401 means access denied) but it612shows how that works.613614By default a black and white error page is shown for each error code.  If615you want to customize the error page, you can use the616:meth:`~flask.Flask.errorhandler` decorator::617618    from flask import render_template619620    @app.errorhandler(404)621    def page_not_found(error):622        return render_template('page_not_found.html'), 404623624Note the ``404`` after the :func:`~flask.render_template` call.  This625tells Flask that the status code of that page should be 404 which means626not found.  By default 200 is assumed which translates to: all went well.627628.. _sessions:629630Sessions631--------632633Besides the request object there is also a second object called634:class:`~flask.session` that allows you to store information specific to a635user from one request to the next.  This is implemented on top of cookies636for you and signs the cookies cryptographically.  What this means is that637the user could look at the contents of your cookie but not modify it,638unless he knows the secret key used for signing.639640In order to use sessions you have to set a secret key.  Here is how641sessions work::642643    from flask import Flask, session, redirect, url_for, escape, request644645    app = Flask(__name__)646647    @app.route('/')648    def index():649        if 'username' in session:650            return 'Logged in as %s' % escape(session['username'])651        return 'You are not logged in'652653    @app.route('/login', methods=['GET', 'POST'])654    def login():655        if request.method == 'POST':656            session['username'] = request.form['username']657            return redirect(url_for('index'))658        return '''659            <form action="" method="post">660                <p><input type=text name=username>661                <p><input type=submit value=Login>662            </form>663        '''664665    @app.route('/logout')666    def logout():667        # remove the username from the session if its there668        session.pop('username', None)669        return redirect(url_for('index'))670671    # set the secret key.  keep this really secret:672    app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'673674The here mentioned :func:`~flask.escape` does escaping for you if you are675not using the template engine (like in this example).676677.. admonition:: How to generate good Secret Keys678679   The problem with random is that it's hard to judge what random is.  And680   a secret key should be as random as possible.  Your operating system681   has ways to generate pretty random stuff based on a cryptographic682   random generator which can be used to get such a key:683684   >>> import os685   >>> os.urandom(24)686   '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'687688   Just take that thing and copy/paste it into your code and you're done.689690Message Flashing691----------------692693Good applications and user interfaces are all about feedback.  If the user694does not get enough feedback he will probably end up hating the695application.  Flask provides a really simple way to give feedback to a696user with the flashing system.  The flashing system basically makes it697possible to record a message at the end of a request and access it next698request and only next request.  This is usually combined with a layout699template that does this.700701To flash a message use the :func:`~flask.flash` method, to get hold of the702messages you can use :func:`~flask.get_flashed_messages` which is also703available in the templates.  Check out the :ref:`message-flashing-pattern`704for a full example.705706Logging707-------708709.. versionadded:: 0.3710711Sometimes you might be in the situation where you deal with data that712should be correct, but actually is not.  For example you have some client713side code that sends an HTTP request to the server, and it's obviously714malformed.  This might be caused by a user tempering with the data, or the715client code failed.  Most the time, it's okay to reply with ``400 Bad716Request`` in that situation, but other times it is not and the code has to717continue working.718719Yet you want to log that something fishy happened.  This is where loggers720come in handy.  As of Flask 0.3 a logger is preconfigured for you to use.721722Here are some example log calls::723724    app.logger.debug('A value for debugging')725    app.logger.warning('A warning occurred (%d apples)', 42)726    app.logger.error('An error occurred')727728The attached :attr:`~flask.Flask.logger` is a standard logging729:class:`~logging.Logger`, so head over to the official stdlib730documentation for more information.