quickstart.rst
This file
Path
docs/quickstart.rst
749 lines · 27.2 KiB
Last changed by
Merge branch 'master' into blueprintsArmin Ronacherbefore adoption3add9c5
History of this fileTake 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 this::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 the official `Jinja2 Template Documentation385<http://jinja.pocoo.org/2/documentation/templates>`_ for more information.386387Here is an example template:388389.. sourcecode:: html+jinja390391 <!doctype html>392 <title>Hello from Flask</title>393 {% if name %}394 <h1>Hello {{ name }}!</h1>395 {% else %}396 <h1>Hello World!</h1>397 {% endif %}398399Inside templates you also have access to the :class:`~flask.request`,400:class:`~flask.session` and :class:`~flask.g` [#]_ objects401as well as the :func:`~flask.get_flashed_messages` function.402403Templates are especially useful if inheritance is used. If you want to404know how that works, head over to the :ref:`template-inheritance` pattern405documentation. Basically template inheritance makes it possible to keep406certain elements on each page (like header, navigation and footer).407408Automatic escaping is enabled, so if name contains HTML it will be escaped409automatically. If you can trust a variable and you know that it will be410safe HTML (because for example it came from a module that converts wiki411markup to HTML) you can mark it as safe by using the412:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the413template. Head over to the Jinja 2 documentation for more examples.414415Here is a basic introduction to how the :class:`~jinja2.Markup` class works:416417>>> from flask import Markup418>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'419Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')420>>> Markup.escape('<blink>hacker</blink>')421Markup(u'<blink>hacker</blink>')422>>> Markup('<em>Marked up</em> » HTML').striptags()423u'Marked up \xbb HTML'424425.. versionchanged:: 0.5426427 Autoescaping is no longer enabled for all templates. The following428 extensions for templates trigger autoescaping: ``.html``, ``.htm``,429 ``.xml``, ``.xhtml``. Templates loaded from a string will have430 autoescaping disabled.431432.. [#] Unsure what that :class:`~flask.g` object is? It's something in which433 you can store information for your own needs, check the documentation of434 that object (:class:`~flask.g`) and the :ref:`sqlite3` for more435 information.436437438Accessing Request Data439----------------------440441For web applications it's crucial to react to the data a client sent to442the server. In Flask this information is provided by the global443:class:`~flask.request` object. If you have some experience with Python444you might be wondering how that object can be global and how Flask445manages to still be threadsafe. The answer are context locals:446447448.. _context-locals:449450Context Locals451``````````````452453.. admonition:: Insider Information454455 If you want to understand how that works and how you can implement456 tests with context locals, read this section, otherwise just skip it.457458Certain objects in Flask are global objects, but not of the usual kind.459These objects are actually proxies to objects that are local to a specific460context. What a mouthful. But that is actually quite easy to understand.461462Imagine the context being the handling thread. A request comes in and the463webserver decides to spawn a new thread (or something else, the464underlying object is capable of dealing with other concurrency systems465than threads as well). When Flask starts its internal request handling it466figures out that the current thread is the active context and binds the467current application and the WSGI environments to that context (thread).468It does that in an intelligent way that one application can invoke another469application without breaking.470471So what does this mean to you? Basically you can completely ignore that472this is the case unless you are doing something like unittesting. You473will notice that code that depends on a request object will suddenly break474because there is no request object. The solution is creating a request475object yourself and binding it to the context. The easiest solution for476unittesting is by using the :meth:`~flask.Flask.test_request_context`477context manager. In combination with the `with` statement it will bind a478test request so that you can interact with it. Here is an example::479480 from flask import request481482 with app.test_request_context('/hello', method='POST'):483 # now you can do something with the request until the484 # end of the with block, such as basic assertions:485 assert request.path == '/hello'486 assert request.method == 'POST'487488The other possibility is passing a whole WSGI environment to the489:meth:`~flask.Flask.request_context` method::490491 from flask import request492493 with app.request_context(environ):494 assert request.method == 'POST'495496The Request Object497``````````````````498499The request object is documented in the API section and we will not cover500it here in detail (see :class:`~flask.request`). Here is a broad overview of501some of the most common operations. First of all you have to import it from502the `flask` module::503504 from flask import request505506The current request method is available by using the507:attr:`~flask.request.method` attribute. To access form data (data508transmitted in a `POST` or `PUT` request) you can use the509:attr:`~flask.request.form` attribute. Here is a full example of the two510attributes mentioned above::511512 @app.route('/login', methods=['POST', 'GET'])513 def login():514 error = None515 if request.method == 'POST':516 if valid_login(request.form['username'],517 request.form['password']):518 return log_the_user_in(request.form['username'])519 else:520 error = 'Invalid username/password'521 # this is executed if the request method was GET or the522 # credentials were invalid523524What happens if the key does not exist in the `form` attribute? In that525case a special :exc:`KeyError` is raised. You can catch it like a526standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request527error page is shown instead. So for many situations you don't have to528deal with that problem.529530To access parameters submitted in the URL (``?key=value``) you can use the531:attr:`~flask.request.args` attribute::532533 searchword = request.args.get('q', '')534535We recommend accessing URL parameters with `get` or by catching the536`KeyError` because users might change the URL and presenting them a 400537bad request page in that case is not user friendly.538539For a full list of methods and attributes of the request object, head over540to the :class:`~flask.request` documentation.541542543File Uploads544````````````545546You can handle uploaded files with Flask easily. Just make sure not to547forget to set the ``enctype="multipart/form-data"`` attribute on your HTML548form, otherwise the browser will not transmit your files at all.549550Uploaded files are stored in memory or at a temporary location on the551filesystem. You can access those files by looking at the552:attr:`~flask.request.files` attribute on the request object. Each553uploaded file is stored in that dictionary. It behaves just like a554standard Python :class:`file` object, but it also has a555:meth:`~werkzeug.datastructures.FileStorage.save` method that allows you to store that556file on the filesystem of the server. Here is a simple example showing how557that works::558559 from flask import request560561 @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/uploaded_file.txt')566 ...567568If you want to know how the file was named on the client before it was569uploaded to your application, you can access the570:attr:`~werkzeug.datastructures.FileStorage.filename` attribute. However please keep in571mind that this value can be forged so never ever trust that value. If you572want to use the filename of the client to store the file on the server,573pass it through the :func:`~werkzeug.utils.secure_filename` function that574Werkzeug provides for you::575576 from flask import request577 from werkzeug import secure_filename578579 @app.route('/upload', methods=['GET', 'POST'])580 def upload_file():581 if request.method == 'POST':582 f = request.files['the_file']583 f.save('/var/www/uploads/' + secure_filename(f.filename))584 ...585586For some better examples, checkout the :ref:`uploading-files` pattern.587588Cookies589```````590591To access cookies you can use the :attr:`~flask.request.cookies`592attribute. Again this is a dictionary with all the cookies the client593transmits. If you want to use sessions, do not use the cookies directly594but instead use the :ref:`sessions` in Flask that add some security on top595of cookies for you.596597598Redirects and Errors599--------------------600601To redirect a user to somewhere else you can use the602:func:`~flask.redirect` function. To abort a request early with an error603code use the :func:`~flask.abort` function. Here an example how this works::604605 from flask import abort, redirect, url_for606607 @app.route('/')608 def index():609 return redirect(url_for('login'))610611 @app.route('/login')612 def login():613 abort(401)614 this_is_never_executed()615616This is a rather pointless example because a user will be redirected from617the index to a page he cannot access (401 means access denied) but it618shows how that works.619620By default a black and white error page is shown for each error code. If621you want to customize the error page, you can use the622:meth:`~flask.Flask.errorhandler` decorator::623624 from flask import render_template625626 @app.errorhandler(404)627 def page_not_found(error):628 return render_template('page_not_found.html'), 404629630Note the ``404`` after the :func:`~flask.render_template` call. This631tells Flask that the status code of that page should be 404 which means632not found. By default 200 is assumed which translates to: all went well.633634.. _sessions:635636Sessions637--------638639Besides the request object there is also a second object called640:class:`~flask.session` that allows you to store information specific to a641user from one request to the next. This is implemented on top of cookies642for you and signs the cookies cryptographically. What this means is that643the user could look at the contents of your cookie but not modify it,644unless he knows the secret key used for signing.645646In order to use sessions you have to set a secret key. Here is how647sessions work::648649 from flask import Flask, session, redirect, url_for, escape, request650651 app = Flask(__name__)652653 @app.route('/')654 def index():655 if 'username' in session:656 return 'Logged in as %s' % escape(session['username'])657 return 'You are not logged in'658659 @app.route('/login', methods=['GET', 'POST'])660 def login():661 if request.method == 'POST':662 session['username'] = request.form['username']663 return redirect(url_for('index'))664 return '''665 <form action="" method="post">666 <p><input type=text name=username>667 <p><input type=submit value=Login>668 </form>669 '''670671 @app.route('/logout')672 def logout():673 # remove the username from the session if its there674 session.pop('username', None)675 return redirect(url_for('index'))676677 # set the secret key. keep this really secret:678 app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'679680The here mentioned :func:`~flask.escape` does escaping for you if you are681not using the template engine (like in this example).682683.. admonition:: How to generate good secret keys684685 The problem with random is that it's hard to judge what random is. And686 a secret key should be as random as possible. Your operating system687 has ways to generate pretty random stuff based on a cryptographic688 random generator which can be used to get such a key:689690 >>> import os691 >>> os.urandom(24)692 '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'693694 Just take that thing and copy/paste it into your code and you're done.695696Message Flashing697----------------698699Good applications and user interfaces are all about feedback. If the user700does not get enough feedback he will probably end up hating the701application. Flask provides a really simple way to give feedback to a702user with the flashing system. The flashing system basically makes it703possible to record a message at the end of a request and access it next704request and only next request. This is usually combined with a layout705template that does this.706707To flash a message use the :func:`~flask.flash` method, to get hold of the708messages you can use :func:`~flask.get_flashed_messages` which is also709available in the templates. Check out the :ref:`message-flashing-pattern`710for a full example.711712Logging713-------714715.. versionadded:: 0.3716717Sometimes you might be in a situation where you deal with data that718should be correct, but actually is not. For example you may have some client719side code that sends an HTTP request to the server but it's obviously720malformed. This might be caused by a user tempering with the data, or the721client code failing. Most of the time, it's okay to reply with ``400 Bad722Request`` in that situation, but sometimes that won't do and the code has723to continue working.724725You may still want to log that something fishy happened. This is where726loggers come in handy. As of Flask 0.3 a logger is preconfigured for you727to use.728729Here are some example log calls::730731 app.logger.debug('A value for debugging')732 app.logger.warning('A warning occurred (%d apples)', 42)733 app.logger.error('An error occurred')734735The attached :attr:`~flask.Flask.logger` is a standard logging736:class:`~logging.Logger`, so head over to the official `logging737documentation <http://docs.python.org/library/logging.html>`_ for more738information.739740Hooking in WSGI Middlewares741---------------------------742743If you want to add a WSGI middleware to your application you can wrap the744internal WSGI application. For example if you want to use one of the745middlewares from the Werkzeug package to work around bugs in lighttpd, you746can do it like this::747748 from werkzeug.contrib.fixers import LighttpdCGIRootFix749 app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)