@ -18,22 +18,7 @@ A minimal Flask application looks something like this::
@app.route('/')
@app.route('/')
def hello_world():
def hello_world():
return 'Hello World!'
return 'Hello, World!'
if __name__ == '__main__':
app.run()
Just save it as `hello.py` (or something similar) and run it with your Python
interpreter. Make sure to not call your application `flask.py` because this
would conflict with Flask itself.
::
$ python hello.py
* Running on http://127.0.0.1:5000/
Now head over to `http://127.0.0.1:5000/ <http://127.0.0.1:5000/> `_ , and you
should see your hello world greeting.
So what did that code do?
So what did that code do?
@ -41,7 +26,7 @@ So what did that code do?
class will be our WSGI application.
class will be our WSGI application.
2. Next we create an instance of this class. The first argument is the name of
2. Next we create an instance of this class. The first argument is the name of
the application's module or package. If you are using a single module (as
the application's module or package. If you are using a single module (as
in this example), you should use `__name__` because depending on if it's
in this example), you should use `` __name__ `` because depending on if it's
started as application or imported as module the name will be different
started as application or imported as module the name will be different
(`` '__main__' `` versus the actual import name). This is needed so that
(`` '__main__' `` versus the actual import name). This is needed so that
Flask knows where to look for templates, static files, and so on. For more
Flask knows where to look for templates, static files, and so on. For more
@ -51,12 +36,34 @@ So what did that code do?
4. The function is given a name which is also used to generate URLs for that
4. The function is given a name which is also used to generate URLs for that
particular function, and returns the message we want to display in the
particular function, and returns the message we want to display in the
user's browser.
user's browser.
5. Finally we use the :meth: `~flask.Flask.run` function to run the local server
with our application. The `` if __name__ == '__main__': `` makes sure the
server only runs if the script is executed directly from the Python
interpreter and not used as an imported module.
To stop the server, hit control-C.
Just save it as :file: `hello.py` or something similar. Make sure to not call
your application :file: `flask.py` because this would conflict with Flask
itself.
To run the application you can either use the :command: `flask` command or
python's `` -m `` switch with Flask. Before you can do that you need
to tell your terminal the application to work with by exporting the
`` FLASK_APP `` environment variable::
$ export FLASK_APP=hello.py
$ flask run
* Running on http://127.0.0.1:5000/
If you are on Windows you need to use `` set `` instead of `` export `` .
Alternatively you can use :command: `python -m flask` ::
$ export FLASK_APP=hello.py
$ python -m flask run
* Running on http://127.0.0.1:5000/
This launches a very simple builtin server, which is good enough for testing
but probably not what you want to use in production. For deployment options see
:ref: `deployment` .
Now head over to `http://127.0.0.1:5000/ <http://127.0.0.1:5000/> `_ , and you
should see your hello world greeting.
.. _public-server:
.. _public-server:
@ -67,37 +74,70 @@ To stop the server, hit control-C.
default because in debugging mode a user of the application can execute
default because in debugging mode a user of the application can execute
arbitrary Python code on your computer.
arbitrary Python code on your computer.
If you have `debug` disabled or trust the users on your network, you can
If you have the debugger disabled or trust the users on your network,
make the server publicly available simply by changing the call of the
you can make the server publicly available simply by adding
:meth: `~flask.Flask.run` method to look like this ::
`` --host=0.0.0.0 `` to the command line ::
app.run(host='0.0.0.0')
flask run --host=0.0.0.0
This tells your operating system to listen on all public IPs.
This tells your operating system to listen on all public IPs.
What to do if the Server does not Start
---------------------------------------
In case the :command: `python -m flask` fails or :command: `flask` does not exist,
there are multiple reasons this might be the case. First of all you need
to look at the error message.
Old Version of Flask
`` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ``
Versions of Flask older than 0.11 use to have different ways to start the
application. In short, the :command: `flask` command did not exist, and
neither did :command: `python -m flask` . In that case you have two options:
either upgrade to newer Flask versions or have a look at the :ref: `server`
docs to see the alternative method for running a server.
Invalid Import Name
`` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ``
The `` FLASK_APP `` environment variable is the name of the module to import at
:command: `flask run` . In case that module is incorrectly named you will get an
import error upon start (or if debug is enabled when you navigate to the
application). It will tell you what it tried to import and why it failed.
The most common reason is a typo or because you did not actually create an
`` app `` object.
.. _debug-mode:
.. _debug-mode:
Debug Mode
Debug Mode
----------
----------
The :meth: `~flask.Flask.run` method is nice to start a local
(Want to just log errors and stack traces? See :ref: `application-errors` )
development server, but you would have to restart it manually after each
change to your code. That is not very nice and Flask can do better. If
you enable debug support the server will reload itself on code changes,
and it will also provide you with a helpful debugger if things go wrong.
There are two ways to enable debugging. Either set that flag on the
The :command: `flask` script is nice to start a local development server, but
application object::
you would have to restart it manually after each change to your code.
That is not very nice and Flask can do better. If you enable debug
support the server will reload itself on code changes, and it will also
provide you with a helpful debugger if things go wrong.
app.debug = True
To enable debug mode you can export the `` FLASK_DEBUG `` environment variabl e
app.run()
before running the server::
Or pass it as a parameter to run::
$ export FLASK_DEBUG=1
$ flask run
app.run(debug=True)
(On Windows you need to use `` set `` instead of `` export `` ).
Both methods have the exact same effect.
This does the following things:
1. it activates the debugger
2. it activates the automatic reloader
3. it enables the debug mode on the Flask application.
There are more parameters that are explained in the :ref: `server` docs.
.. admonition :: Attention
.. admonition :: Attention
@ -119,14 +159,11 @@ Have another debugger in mind? See :ref:`working-with-debuggers`.
Routing
Routing
-------
-------
Modern web applications have beautiful URLs. This helps people remember
Modern web applications use meaningful URLs to help users. Users are more
the URLs, which is especially handy for applications that are used from
likely to like a page and come back if the page uses a meaningful URL they can
mobile devices with slower network connections. If the user can directly
remember and use to directly visit a page.
go to the desired page without having to hit the index page it is more
likely they will like the page and come back next time.
As you have seen above, the :meth: `~flask.Flask.route` decorator is used to
Use the :meth: `~flask.Flask.route` decorator to bind a function to a URL. ::
bind a function to a URL. Here are some basic examples::
@app.route('/')
@app.route('/')
def index():
def index():
@ -134,18 +171,18 @@ bind a function to a URL. Here are some basic examples::
@app.route('/hello')
@app.route('/hello')
def hello():
def hello():
return 'Hello World'
return 'Hello, World'
But there is more to it! You can make certain parts of the URL dynamic and
You can do more! You can make parts of the URL dynamic and attach multiple
attach multiple rules to a function.
rules to a function.
Variable Rules
Variable Rules
`` ` ` ` ` ` ` ` ` ` ` ``
`` ` ` ` ` ` ` ` ` ` ` ``
To add variable parts to a URL you can mark these special sections as
You can add variable sections to a URL by marking sections with
`` <variable_name> `` . Such a part is then passed as a keyword argument to your
`` <variable_name> `` . Your function then receives the `` <variable_name> ``
function. Optionally a converter can be used by specifying a rule with
as a keyword argument. Optionally, you can use a converter to specify the type
`` <converter:variable_name> `` . Here are some nice examples ::
of the argument like `` <converter:variable_name> `` . ::
@app.route('/user/<username>')
@app.route('/user/<username>')
def show_user_profile(username):
def show_user_profile(username):
@ -157,108 +194,111 @@ function. Optionally a converter can be used by specifying a rule with
# show the post with the given id, the id is an integer
# show the post with the given id, the id is an integer
return 'Post %d' % post_id
return 'Post %d' % post_id
The following converters exist:
@app.route('/path/<path:subpath>')
def show_subpath(subpath):
=========== ===========================================
# show the subpath after /path/
`int` accepts integers
return 'Subpath %s' % subpath
`float` like `int` but for floating point values
`path` like the default but also accepts slashes
=========== ===========================================
.. admonition :: Unique URLs / Redirection Behavior
Converter types:
Flask's URL rules are based on Werkzeug's routing module. The idea
========== ==========================================
behind that module is to ensure beautiful and unique URLs based on
`` string `` (default) accepts any text without a slash
precedents laid down by Apache and earlier HTTP servers.
`` int `` accepts positive integers
`` float `` accepts positive floating point values
`` path `` like `` string `` but also accepts slashes
`` uuid `` accepts UUID strings
========== ==========================================
Take these two rules::
Unique URLs / Redirection Behavior
`` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ``
@app.route('/projects/')
Take these two rules::
def projects():
return 'The project page'
@app.route('/about ')
@app.route('/projects/')
def about ():
def projects ():
return 'The abou t page'
return 'The projec t page'
Though they look rather similar, they differ in their use of the trailing
@app.route('/about')
slash in the URL *definition* . In the first case, the canonical URL for the
def about():
`projects` endpoint has a trailing slash. In that sense, it is similar to
return 'The about page'
a folder on a file system. Accessing it without a trailing slash will cause
Flask to redirect to the canonical URL with the trailing slash.
In the second case, however, the URL is defined without a trailing slash,
Though they look similar, they differ in their use of the trailing slash in
rather like the pathname of a file on UNIX-like systems. Accessing the URL
the URL. In the first case, the canonical URL for the `` projects `` endpoint
with a trailing slash will produce a 404 "Not Found" error.
uses a trailing slash. It's similar to a folder in a file system; if you
access the URL without a trailing slash, Flask redirects you to the
canonical URL with the trailing slash.
This behavior allows relative URLs to continue working even if the trailing
In the second case, however, the URL definition lacks a trailing slash,
slash is omitted, consistent with how Apache and other servers work. Also,
like the pathname of a file on UNIX-like systems. Accessing the URL with a
the URLs will stay unique, which helps search engines avoid indexing the
trailing slash produces a 404 “Not Found” error.
same page twice.
This behavior allows relative URLs to continue working even if the trailing
slash is omitted, consistent with how Apache and other servers work. Also,
the URLs will stay unique, which helps search engines avoid indexing the
same page twice.
.. _url-building:
.. _url-building:
URL Building
URL Building
`` ` ` ` ` ` ` ` ` ``
`` ` ` ` ` ` ` ` ` ``
If it can match URLs, can Flask also generate them? Of course it can. To
To build a URL to a specific function, use the :func: `~flask.url_for` function.
build a URL to a specific function you can use the :func: `~flask.url_for`
It accepts the name of the function as its first argument and any number of
function. It accepts the name of the function as first argument and a number
keyword arguments, each corresponding to a variable part of the URL rule.
of keyword arguments, each corresponding to the variable part of the URL rule.
Unknown variable parts are appended to the URL as query parameters.
Unknown variable parts are appended to the URL as query parameters. Here are
some examples:
>>> from flask import Flask, url_for
>>> app = Flask(__name__)
>>> @app.route('/')
... def index(): pass
...
>>> @app.route('/login')
... def login(): pass
...
>>> @app.route('/user/<username>')
... def profile(username): pass
...
>>> with app.test_request_context():
... print url_for('index')
... print url_for('login')
... print url_for('login', next='/')
... print url_for('profile', username='John Doe')
...
/
/login
/login?next=/
/user/John%20Doe
(This also uses the :meth: `~flask.Flask.test_request_context` method, explained
below. It tells Flask to behave as though it is handling a request, even
though we are interacting with it through a Python shell. Have a look at the
explanation below. :ref: `context-locals` ).
Why would you want to build URLs using the URL reversing function :func: `~flask.url_for`
instead of hard-coding them into your templates? There are three good reasons
for this:
1. Reversing is often more descriptive than hard-coding the URLs. More
importantly, it allows you to change URLs in one go, without having to
remember to change URLs all over the place.
2. URL building will handle escaping of special characters and Unicode
data transparently for you, so you don't have to deal with them.
3. If your application is placed outside the URL root (say, in
`` /myapplication `` instead of `` / `` ), :func: `~flask.url_for` will handle
that properly for you.
Why would you want to build URLs using the URL reversing function
:func: `~flask.url_for` instead of hard-coding them into your templates?
1. Reversing is often more descriptive than hard-coding the URLs.
2. You can change your URLs in one go instead of needing to remember to
manually change hard-coded URLs.
3. URL building handles escaping of special characters and Unicode data
transparently.
4. If your application is placed outside the URL root, for example, in
`` /myapplication `` instead of `` / `` , :func: `~flask.url_for` properly
handles that for you.
For example, here we use the :meth: `~flask.Flask.test_request_context` method
to try out :func: `~flask.url_for` . :meth: `~flask.Flask.test_request_context`
tells Flask to behave as though it's handling a request even while we use a
Python shell. See :ref: `context-locals` . ::
from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def index():
return 'index'
@app.route('/login')
def login():
return 'login'
@app.route('/user/<username>')
def profile(username):
return '{}'s profile'.format(username)
with app.test_request_context():
print(url_for('index'))
print(url_for('login'))
print(url_for('login', next='/'))
print(url_for('profile', username='John Doe'))
/
/login
/login?next=/
/user/John%20Doe
HTTP Methods
HTTP Methods
`` ` ` ` ` ` ` ` ` ``
`` ` ` ` ` ` ` ` ` ``
HTTP (the protocol web applications are speaking) knows different methods for
Web applications use different HTTP methods when accessing URLs. You should
accessing URLs. By default, a route only answers to `GET` requests, but that
familiarize yourself with the HTTP methods as you work with Flask. By default,
can be changed by providing the `methods` argument to the
a route only answers to `` GET `` requests. You can use the `` methods `` argument
:meth: `~flask.Flask.route` decorator. Here are some examples::
of the :meth: `~flask.Flask.route` decorator to handle different HTTP methods.
::
from flask import request
@app.route('/login', methods=['GET', 'POST'])
@app.route('/login', methods=['GET', 'POST'])
def login():
def login():
@ -267,64 +307,11 @@ can be changed by providing the `methods` argument to the
else:
else:
show_the_login_form()
show_the_login_form()
If `GET` is present, `HEAD` will be added automatically for you. You
If `` GET `` is present, Flask automatically adds support for the `` HEAD `` method
don't have to deal with that. It will also make sure that `HEAD` requests
and handles `` HEAD `` requests according to the the `HTTP RFC`_ . Likewise,
are handled as the `HTTP RFC`_ (the document describing the HTTP
`` OPTIONS `` is automatically implemented for you.
protocol) demands, so you can completely ignore that part of the HTTP
specification. Likewise, as of Flask 0.6, `OPTIONS` is implemented for you
.. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt
automatically as well.
You have no idea what an HTTP method is? Worry not, here is a quick
introduction to HTTP methods and why they matter:
The HTTP method (also often called "the verb") tells the server what the
clients wants to *do* with the requested page. The following methods are
very common:
`GET`
The browser tells the server to just *get* the information stored on
that page and send it. This is probably the most common method.
`HEAD`
The browser tells the server to get the information, but it is only
interested in the *headers* , not the content of the page. An
application is supposed to handle that as if a `GET` request was
received but to not deliver the actual content. In Flask you don't
have to deal with that at all, the underlying Werkzeug library handles
that for you.
`POST`
The browser tells the server that it wants to *post* some new
information to that URL and that the server must ensure the data is
stored and only stored once. This is how HTML forms usually
transmit data to the server.
`PUT`
Similar to `POST` but the server might trigger the store procedure
multiple times by overwriting the old values more than once. Now you
might be asking why this is useful, but there are some good reasons
to do it this way. Consider that the connection is lost during
transmission: in this situation a system between the browser and the
server might receive the request safely a second time without breaking
things. With `POST` that would not be possible because it must only
be triggered once.
`DELETE`
Remove the information at the given location.
`OPTIONS`
Provides a quick way for a client to figure out which methods are
supported by this URL. Starting with Flask 0.6, this is implemented
for you automatically.
Now the interesting part is that in HTML4 and XHTML1, the only methods a
form can submit to the server are `GET` and `POST` . But with JavaScript
and future HTML standards you can use the other methods as well. Furthermore
HTTP has become quite popular lately and browsers are no longer the only
clients that are using HTTP. For instance, many revision control systems
use it.
.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt
Static Files
Static Files
------------
------------
@ -332,14 +319,14 @@ Static Files
Dynamic web applications also need static files. That's usually where
Dynamic web applications also need static files. That's usually where
the CSS and JavaScript files are coming from. Ideally your web server is
the CSS and JavaScript files are coming from. Ideally your web server is
configured to serve them for you, but during development Flask can do that
configured to serve them for you, but during development Flask can do that
as well. Just create a folder called `static` in your package or next to
as well. Just create a folder called :file: `static` in your package or next to
your module and it will be available at `/static` on the application.
your module and it will be available at `` /static `` on the application.
To generate URLs for static files, use the special `` 'static' `` endpoint name::
To generate URLs for static files, use the special `` 'static' `` endpoint name::
url_for('static', filename='style.css')
url_for('static', filename='style.css')
The file has to be stored on the filesystem as `` static/style.css ` ` .
The file has to be stored on the filesystem as :file: `static/style.css ` .
Rendering Templates
Rendering Templates
-------------------
-------------------
@ -347,7 +334,7 @@ Rendering Templates
Generating HTML from within Python is not fun, and actually pretty
Generating HTML from within Python is not fun, and actually pretty
cumbersome because you have to do the HTML escaping on your own to keep
cumbersome because you have to do the HTML escaping on your own to keep
the application secure. Because of that Flask configures the `Jinja2
the application secure. Because of that Flask configures the `Jinja2
<http://jinja.pocoo.org/2/ > `_ template engine for you automatically.
<http://jinja.pocoo.org/> `_ template engine for you automatically.
To render a template you can use the :func: `~flask.render_template`
To render a template you can use the :func: `~flask.render_template`
method. All you have to do is provide the name of the template and the
method. All you have to do is provide the name of the template and the
@ -361,7 +348,7 @@ Here's a simple example of how to render a template::
def hello(name=None):
def hello(name=None):
return render_template('hello.html', name=name)
return render_template('hello.html', name=name)
Flask will look for templates in the `templates` folder. So if your
Flask will look for templates in the :file: `templates` folder. So if your
application is a module, this folder is next to that module, if it's a
application is a module, this folder is next to that module, if it's a
package it's actually inside your package:
package it's actually inside your package:
@ -380,7 +367,7 @@ package it's actually inside your package:
For templates you can use the full power of Jinja2 templates. Head over
For templates you can use the full power of Jinja2 templates. Head over
to the official `Jinja2 Template Documentation
to the official `Jinja2 Template Documentation
<http://jinja.pocoo.org/2/documentation /templates> `_ for more information.
<http://jinja.pocoo.org/docs /templates> `_ for more information.
Here is an example template:
Here is an example template:
@ -391,7 +378,7 @@ Here is an example template:
{% if name %}
{% if name %}
<h1>Hello {{ name }}!</h1>
<h1>Hello {{ name }}!</h1>
{% else %}
{% else %}
<h1>Hello World!</h1>
<h1>Hello, World!</h1>
{% endif %}
{% endif %}
Inside templates you also have access to the :class: `~flask.request` ,
Inside templates you also have access to the :class: `~flask.request` ,
@ -403,22 +390,22 @@ know how that works, head over to the :ref:`template-inheritance` pattern
documentation. Basically template inheritance makes it possible to keep
documentation. Basically template inheritance makes it possible to keep
certain elements on each page (like header, navigation and footer).
certain elements on each page (like header, navigation and footer).
Automatic escaping is enabled, so if `name` contains HTML it will be escaped
Automatic escaping is enabled, so if `` name `` contains HTML it will be escaped
automatically. If you can trust a variable and you know that it will be
automatically. If you can trust a variable and you know that it will be
safe HTML (for example because it came from a module that converts wiki
safe HTML (for example because it came from a module that converts wiki
markup to HTML) you can mark it as safe by using the
markup to HTML) you can mark it as safe by using the
:class: `~jinja2.Markup` class or by using the `` |safe `` filter in the
:class: `~jinja2.Markup` class or by using the `` |safe `` filter in the
template. Head over to the Jinja 2 documentation for more examples.
template. Head over to the Jinja 2 documentation for more examples.
Here is a basic introduction to how the :class: `~jinja2.Markup` class works:
Here is a basic introduction to how the :class: `~jinja2.Markup` class works::
>>> from flask import Markup
>>> from flask import Markup
>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'
>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'
Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')
Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')
>>> Markup.escape('<blink>hacker</blink>')
>>> Markup.escape('<blink>hacker</blink>')
Markup(u'<blink>hacker</blink>')
Markup(u'<blink>hacker</blink>')
>>> Markup('<em>Marked up</em> » HTML').striptags()
>>> Markup('<em>Marked up</em> » HTML').striptags()
u'Marked up \xbb HTML'
u'Marked up \xbb HTML'
.. versionchanged :: 0.5
.. versionchanged :: 0.5
@ -436,7 +423,7 @@ u'Marked up \xbb HTML'
Accessing Request Data
Accessing Request Data
----------------------
----------------------
For web applications it's crucial to react to the data a client sent to
For web applications it's crucial to react to the data a client sends to
the server. In Flask this information is provided by the global
the server. In Flask this information is provided by the global
:class: `~flask.request` object. If you have some experience with Python
:class: `~flask.request` object. If you have some experience with Python
you might be wondering how that object can be global and how Flask
you might be wondering how that object can be global and how Flask
@ -472,7 +459,7 @@ will notice that code which depends on a request object will suddenly break
because there is no request object. The solution is creating a request
because there is no request object. The solution is creating a request
object yourself and binding it to the context. The easiest solution for
object yourself and binding it to the context. The easiest solution for
unit testing is to use the :meth: `~flask.Flask.test_request_context`
unit testing is to use the :meth: `~flask.Flask.test_request_context`
context manager. In combination with the `with` statement it will bind a
context manager. In combination with the `` with `` statement it will bind a
test request so that you can interact with it. Here is an example::
test request so that you can interact with it. Here is an example::
from flask import request
from flask import request
@ -495,16 +482,16 @@ The Request Object
`` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ``
`` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ``
The request object is documented in the API section and we will not cover
The request object is documented in the API section and we will not cover
it here in detail (see :class: `~flask.r equest` ). Here is a broad overview of
it here in detail (see :class: `~flask.R equest` ). Here is a broad overview of
some of the most common operations. First of all you have to import it from
some of the most common operations. First of all you have to import it from
the `flask` module::
the `` flask `` module::
from flask import request
from flask import request
The current request method is available by using the
The current request method is available by using the
:attr: `~flask.r equest.method` attribute. To access form data (data
:attr: `~flask.R equest.method` attribute. To access form data (data
transmitted in a `POST` or `PUT` request) you can use the
transmitted in a `` POST `` or `` PUT `` request) you can use the
:attr: `~flask.r equest.form` attribute. Here is a full example of the two
:attr: `~flask.R equest.form` attribute. Here is a full example of the two
attributes mentioned above::
attributes mentioned above::
@app.route('/login', methods=['POST', 'GET'])
@app.route('/login', methods=['POST', 'GET'])
@ -520,23 +507,23 @@ attributes mentioned above::
# was GET or the credentials were invalid
# was GET or the credentials were invalid
return render_template('login.html', error=error)
return render_template('login.html', error=error)
What happens if the key does not exist in the `form` attribute? In that
What happens if the key does not exist in the `` form `` attribute? In that
case a special :exc: `KeyError` is raised. You can catch it like a
case a special :exc: `KeyError` is raised. You can catch it like a
standard :exc: `KeyError` but if you don't do that, a HTTP 400 Bad Request
standard :exc: `KeyError` but if you don't do that, a HTTP 400 Bad Request
error page is shown instead. So for many situations you don't have to
error page is shown instead. So for many situations you don't have to
deal with that problem.
deal with that problem.
To access parameters submitted in the URL (`` ?key=value `` ) you can use the
To access parameters submitted in the URL (`` ?key=value `` ) you can use the
:attr: `~flask.r equest.args` attribute::
:attr: `~flask.R equest.args` attribute::
searchword = request.args.get('key', '')
searchword = request.args.get('key', '')
We recommend accessing URL parameters with `get` or by catching the
We recommend accessing URL parameters with `get` or by catching the
`KeyError` because users might change the URL and presenting them a 400
:exc: `KeyError` because users might change the URL and presenting them a 400
bad request page in that case is not user friendly.
bad request page in that case is not user friendly.
For a full list of methods and attributes of the request object, head over
For a full list of methods and attributes of the request object, head over
to the :class: `~flask.r equest` documentation.
to the :class: `~flask.R equest` documentation.
File Uploads
File Uploads
@ -573,7 +560,7 @@ pass it through the :func:`~werkzeug.utils.secure_filename` function that
Werkzeug provides for you::
Werkzeug provides for you::
from flask import request
from flask import request
from werkzeug import secure_filename
from werkzeug.utils import secure_filename
@app.route('/upload', methods=['GET', 'POST'])
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
def upload_file():
@ -662,6 +649,8 @@ Note the ``404`` after the :func:`~flask.render_template` call. This
tells Flask that the status code of that page should be 404 which means
tells Flask that the status code of that page should be 404 which means
not found. By default 200 is assumed which translates to: all went well.
not found. By default 200 is assumed which translates to: all went well.
See :ref: `error-handlers` for more details.
.. _about-responses:
.. _about-responses:
About Responses
About Responses
@ -670,7 +659,7 @@ About Responses
The return value from a view function is automatically converted into a
The return value from a view function is automatically converted into a
response object for you. If the return value is a string it's converted
response object for you. If the return value is a string it's converted
into a response object with the string as response body, a `` 200 OK ``
into a response object with the string as response body, a `` 200 OK ``
status code and a `` text/html ` ` mimetype. The logic that Flask applies to
status code and a :mimetype: `text/html ` mimetype. The logic that Flask applies to
converting return values into response objects is as follows:
converting return values into response objects is as follows:
1. If a response object of the correct type is returned it's directly
1. If a response object of the correct type is returned it's directly
@ -680,17 +669,15 @@ converting return values into response objects is as follows:
3. If a tuple is returned the items in the tuple can provide extra
3. If a tuple is returned the items in the tuple can provide extra
information. Such tuples have to be in the form `` (response, status,
information. Such tuples have to be in the form `` (response, status,
headers)`` or ` ` (response, headers) `` where at least one item has
headers)`` or ` ` (response, headers) `` where at least one item has
to be in the tuple. The `status` value will override the status code
to be in the tuple. The `` status `` value will override the status code
and `headers` can be a list or dictionary of additional header values.
and `` headers `` can be a list or dictionary of additional header values.
4. If none of that works, Flask will assume the return value is a
4. If none of that works, Flask will assume the return value is a
valid WSGI application and convert that into a response object.
valid WSGI application and convert that into a response object.
If you want to get hold of the resulting response object inside the view
If you want to get hold of the resulting response object inside the view
you can use the :func: `~flask.make_response` function.
you can use the :func: `~flask.make_response` function.
Imagine you have a view like this:
Imagine you have a view like this::
.. sourcecode :: python
@app.errorhandler(404)
@app.errorhandler(404)
def not_found(error):
def not_found(error):
@ -698,9 +685,7 @@ Imagine you have a view like this:
You just need to wrap the return expression with
You just need to wrap the return expression with
:func: `~flask.make_response` and get the response object to modify it, then
:func: `~flask.make_response` and get the response object to modify it, then
return it:
return it::
.. sourcecode :: python
@app.errorhandler(404)
@app.errorhandler(404)
def not_found(error):
def not_found(error):
@ -739,7 +724,7 @@ sessions work::
session['username'] = request.form['username']
session['username'] = request.form['username']
return redirect(url_for('index'))
return redirect(url_for('index'))
return '''
return '''
<form action="" method="post">
<form method="post">
<p><input type=text name=username>
<p><input type=text name=username>
<p><input type=submit value=Login>
<p><input type=submit value=Login>
</form>
</form>
@ -762,13 +747,13 @@ not using the template engine (as in this example).
The problem with random is that it's hard to judge what is truly random. And
The problem with random is that it's hard to judge what is truly random. And
a secret key should be as random as possible. Your operating system
a secret key should be as random as possible. Your operating system
has ways to generate pretty random stuff based on a cryptographic
has ways to generate pretty random stuff based on a cryptographic
random generator which can be used to get such a key:
random generator which can be used to get such a key::
>>> import os
>>> import os
>>> os.urandom(24)
>>> os.urandom(24)
'\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'
'\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'
Just take that thing and copy/paste it into your code and you're done.
Just take that thing and copy/paste it into your code and you're done.
A note on cookie-based sessions: Flask will take the values you put into the
A note on cookie-based sessions: Flask will take the values you put into the
session object and serialize them into a cookie. If you are finding some
session object and serialize them into a cookie. If you are finding some
@ -776,6 +761,9 @@ values do not persist across requests, cookies are indeed enabled, and you are
not getting a clear error message, check the size of the cookie in your page
not getting a clear error message, check the size of the cookie in your page
responses compared to the size supported by web browsers.
responses compared to the size supported by web browsers.
Besides the default client-side based sessions, if you want to handle
sessions on the server-side instead, there are several
Flask extensions that support this.
Message Flashing
Message Flashing
----------------
----------------
@ -818,9 +806,11 @@ Here are some example log calls::
The attached :attr: `~flask.Flask.logger` is a standard logging
The attached :attr: `~flask.Flask.logger` is a standard logging
:class: `~logging.Logger` , so head over to the official `logging
:class: `~logging.Logger` , so head over to the official `logging
documentation <http://docs.python.org/library/logging.html>`_ for more
documentation <https ://docs.python.org/library/logging.html>`_ for more
information.
information.
Read more on :ref: `application-errors` .
Hooking in WSGI Middlewares
Hooking in WSGI Middlewares
---------------------------
---------------------------
@ -832,24 +822,16 @@ can do it like this::
from werkzeug.contrib.fixers import LighttpdCGIRootFix
from werkzeug.contrib.fixers import LighttpdCGIRootFix
app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)
app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)
.. _quickstart_deployment:
Using Flask Extensions
----------------------
Deploying to a Web Server
-------------------------
Ready to deploy your new Flask app? To wrap up the quickstart, you can
immediately deploy to a hosted platform, all of which offer a free plan for
small projects:
- `Deploying Flask on Heroku <http://devcenter.heroku.com/articles/python> `_
Extensions are packages that help you accomplish common tasks. For
- `Deploying WSGI on dotCloud <http://docs.dotcloud.com/services/python/> `_
example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple
with `Flask-specific notes <http://flask.pocoo.org/snippets/48/> `_
and easy to use with Flask.
Other places where you can host your Flask app:
For more on Flask extensions, have a look at :ref: `extensions` .
- `Deploying Flask on Webfaction <http://flask.pocoo.org/snippets/65/> `_
Deploying to a Web Server
- `Deploying Flask on Google App Engine <https://github.com/kamalgill/flask-appengine-template> `_
-------------------------
- `Sharing your Localhost Server with Localtunnel <http://flask.pocoo.org/snippets/89/> `_
If you manage your own hosts and would like to host yourself, see the chapter
Ready to deploy your new Flask app? Go to :ref: `deployment` .
on :ref: `deployment` .