This part of the documentation covers all the interfaces of Flask. For parts where Flask depends on external libraries, we document the most important right here and provide links to the canonical documentation.
The flask object implements a WSGI application and acts as the central object. It is passed the name of the module or package of the application. Once it is created it will act as a central registry for the view functions, the URL rules, template configuration and much more.
The name of the package is used to resolve resources from inside the package or the folder the module is contained in depending on if the package parameter resolves to an actual python package (a folder with an __init__.py file inside) or a standard module (just a .py file).
For more information about resource loading, see open_resource().
Usually you create a Flask instance in your main module or in the __init__.py file of your package like this:
from flask import Flask
app = Flask(__name__)
Connects a URL rule. Works exactly like the route() decorator. If a view_func is provided it will be registered with the endpoint.
Basically this example:
@app.route('/')
def index():
pass
Is equivalent to the following:
def index():
pass
app.add_url_rule('/', 'index', index)
If the view_func is not provided you will need to connect the endpoint to a view function like so:
app.view_functions['index'] = index
Changed in version 0.2: view_func parameter added.
Parameters: |
|
---|
the debug flag. Set this to True to enable debugging of the application. In debug mode the debugger will kick in when an unhandled exception ocurrs and the integrated server will automatically reload the application if changes in the code are detected.
This attribute can also be configured from the config with the DEBUG configuration key. Defaults to False.
the logging format used for the debug logger. This is only used when the application is in debug mode, otherwise the attached logging handler does the formatting.
New in version 0.3.
A decorator that is used to register a function give a given error code. Example:
@app.errorhandler(404)
def page_not_found(error):
return 'This page does not exist', 404
You can also register a function as error handler without using the errorhandler() decorator. The following example is equivalent to the one above:
def page_not_found(error):
return 'This page does not exist', 404
app.error_handlers[404] = page_not_found
Parameters: |
|
---|
A logging.Logger object for this application. The default configuration is to log to stderr if the application is in debug mode. This logger can be used to (surprise) log messages. Here some examples:
app.logger.debug('A value for debugging')
app.logger.warning('A warning ocurred (%d apples)', 42)
app.logger.error('An error occoured')
New in version 0.3.
Converts the return value from a view function to a real response object that is an instance of response_class.
The following types are allowed for rv:
response_class | the object is returned unchanged |
str | a response object is created with the string as body |
unicode | a response object is created with the string encoded to utf-8 as body |
tuple | the response object is created with the contents of the tuple as arguments |
a WSGI function | the function is called as WSGI application and buffered as response object |
Parameters: |
|
---|
Opens a resource from the application’s resource folder. To see how this works, consider the following folder structure:
/myapplication.py
/schemal.sql
/static
/style.css
/template
/layout.html
/index.html
If you want to open the schema.sql file you would do the following:
with app.open_resource('schema.sql') as f:
contents = f.read()
do_something_with(contents)
Parameters: |
|
---|
Creates or opens a new session. Default implementation stores all session data in a signed cookie. This requires that the secret_key is set.
Parameters: |
|
---|
A timedelta which is used to set the expiration date of a permanent session. The default is 31 days which makes a permanent session survive for roughly one month.
This attribute can also be configured from the config with the PERMANENT_SESSION_LIFETIME configuration key. Defaults to timedelta(days=31)
Can be overridden in order to modify the response object before it’s sent to the WSGI server. By default this will call all the after_request() decorated functions.
Parameters: |
|
---|---|
Returns: | a new response object or the same, has to be an instance of response_class. |
Creates a request context from the given environment and binds it to the current context. This must be used in combination with the with statement because the request is only bound to the current context for the duration of the with block.
Example usage:
with app.request_context(environ):
do_something_with(request)
The object returned can also be used without the with statement which is useful for working in the shell. The example above is doing exactly the same as this code:
ctx = app.request_context(environ)
ctx.push()
try:
do_something_with(request)
finally:
ctx.pop()
The big advantage of this approach is that you can use it without the try/finally statement in a shell for interactive testing:
>>> ctx = app.test_request_context()
>>> ctx.bind()
>>> request.path
u'/'
>>> ctx.unbind()
Changed in version 0.3: Added support for non-with statement usage and with statement is now passed the ctx object.
Parameters: |
|
---|
A decorator that is used to register a view function for a given URL rule. Example:
@app.route('/')
def index():
return 'Hello World'
Variables parts in the route can be specified with angular brackets (/user/<username>). By default a variable part in the URL accepts any string without a slash however a different converter can be specified as well by using <converter:name>.
Variable parts are passed to the view function as keyword arguments.
The following converters are possible:
int | accepts integers |
float | like int but for floating point values |
path | like the default but also accepts slashes |
Here some examples:
@app.route('/')
def index():
pass
@app.route('/<username>')
def show_user(username):
pass
@app.route('/post/<int:post_id>')
def show_post(post_id):
pass
An important detail to keep in mind is how Flask deals with trailing slashes. The idea is to keep each URL unique so the following rules apply:
This is consistent with how web servers deal with static files. This also makes it possible to use relative link targets safely.
The route() decorator accepts a couple of other arguments as well:
Parameters: |
|
---|
Runs the application on a local development server. If the debug flag is set the server will automatically reload for code changes and show a debugger in case an exception happened.
Parameters: |
|
---|
Saves the session if it needs updates. For the default implementation, check open_session().
Parameters: |
|
---|
if a secret key is set, cryptographic components can use this to sign cookies and other things. Set this to a complex random value when you want to use the secure cookie for instance.
This attribute can also be configured from the config with the SECRET_KEY configuration key. Defaults to None.
The secure cookie uses this for the name of the session cookie
This attribute can also be configured from the config with the SESSION_COOKIE_NAME configuration key. Defaults to 'session'
A decorator that is used to register custom template filter. You can specify a name for the filter, otherwise the function name will be used. Example:
@app.template_filter()
def reverse(s):
return s[::-1]
Parameters: |
|
---|
Update the template context with some commonly used variables. This injects request, session and g into the template context.
Parameters: |
|
---|
the Map for this instance. You can use this to change the routing converters after the class was created but before any routes are connected. Example:
from werkzeug import BaseConverter
class ListConverter(BaseConverter):
def to_python(self, value):
return value.split(',')
def to_url(self, values):
return ','.join(BaseConverter.to_url(value)
for value in values)
app = Flask(__name__)
app.url_map.converters['list'] = ListConverter
Enable this if you want to use the X-Sendfile feature. Keep in mind that the server has to support this. This only affects files sent with the send_file() method.
New in version 0.2.
This attribute can also be configured from the config with the USE_X_SENDFILE configuration key. Defaults to False.
The actual WSGI application. This is not implemented in __call__ so that middlewares can be applied without losing a reference to the class. So instead of doing this:
app = MyMiddleware(app)
It’s a better idea to do this instead:
app.wsgi_app = MyMiddleware(app.wsgi_app)
Then you still have the original application object around and can continue to call methods on it.
Parameters: |
|
---|
Container object that enables pluggable applications. A module can be used to organize larger applications. They represent blueprints that, in combination with a Flask object are used to create a large application.
A module is like an application bound to an import_name. Multiple modules can share the same import names, but in that case a name has to be provided to keep them apart. If different import names are used, the rightmost part of the import name is used as name.
Here an example structure for a larger appliation:
/myapplication
/__init__.py
/views
/__init__.py
/admin.py
/frontend.py
The myapplication/__init__.py can look like this:
from flask import Flask
from myapplication.views.admin import admin
from myapplication.views.frontend import frontend
app = Flask(__name__)
app.register_module(admin, url_prefix='/admin')
app.register_module(frontend)
And here an example view module (myapplication/views/admin.py):
from flask import Module
admin = Module(__name__)
@admin.route('/')
def index():
pass
@admin.route('/login')
def login():
pass
For a gentle introduction into modules, checkout the Working with Modules section.
Opens a resource from the application’s resource folder. To see how this works, consider the following folder structure:
/myapplication.py
/schemal.sql
/static
/style.css
/template
/layout.html
/index.html
If you want to open the schema.sql file you would do the following:
with app.open_resource('schema.sql') as f:
contents = f.read()
do_something_with(contents)
Parameters: |
|
---|
The request object used by default in flask. Remembers the matched endpoint and view arguments.
It is what ends up as request. If you want to replace the request object used you can subclass this and set request_class to your subclass.
To access incoming request data, you can use the global request object. Flask parses incoming request data for you and gives you access to it through that global object. Internally Flask makes sure that you always get the correct data for the active thread if you are in a multithreaded environment.
The request object is an instance of a Request subclass and provides all of the attributes Werkzeug defines. This just shows a quick overview of the most important ones.
Provides different ways to look at the current URL. Imagine your application is listening on the following URL:
http://www.example.com/myapplication
And a user requests the following URL:
http://www.example.com/myapplication/page.html?x=y
In this case the values of the above mentioned attributes would be the following:
path | /page.html |
script_root | /myapplication |
base_url | http://www.example.com/myapplication/page.html |
url | http://www.example.com/myapplication/page.html?x=y |
url_root | http://www.example.com/myapplication/ |
The response object that is used by default in flask. Works like the response object from Werkzeug but is set to have a HTML mimetype by default. Quite often you don’t have to create this object yourself because make_response() will take care of that for you.
If you want to replace the response object used you can subclass this and set response_class to your subclass.
Sets a cookie. The parameters are the same as in the cookie Morsel object in the Python standard library but it accepts unicode data, too.
Parameters: |
|
---|
The string representation of the request body. Whenever you access this property the request iterable is encoded and flattened. This can lead to unwanted behavior if you stream big data.
This behavior can be disabled by setting implicit_sequence_conversion to False.
If you have the Flask.secret_key set you can use sessions in Flask applications. A session basically makes it possible to remember information from one request to another. The way Flask does this is by using a signed cookie. So the user can look at the session contents, but not modify it unless he knows the secret key, so make sure to set that to something complex and unguessable.
To access the current session you can use the session object:
The session object works pretty much like an ordinary dict, with the difference that it keeps track on modifications.
The following attributes are interesting:
True if the session object detected a modification. Be advised that modifications on mutable structures are not picked up automatically, in that situation you have to explicitly set the attribute to True yourself. Here an example:
# this change is not picked up because a mutable object (here # a list) is changed. session['objects'].append(42) # so mark it as modified yourself session.modified = True
To share data that is valid for one request only from one function to another, a global variable is not good enough because it would break in threaded environments. Flask provides you with a special object that ensures it is only valid for the active request and that will return different values for each request. In a nutshell: it does the right thing, like it does for request and session.
Generates a URL to the given endpoint with the method provided. The endpoint is relative to the active module if modules are in use.
Here some examples:
Active Module | Target Endpoint | Target Function |
---|---|---|
None | 'index' | index of the application |
None | '.index' | index of the application |
'admin' | 'index' | index of the admin module |
any | '.index' | index of the application |
any | 'admin.index' | index of the admin module |
Variable arguments that are unknown to the target endpoint are appended to the generated URL as query arguments.
For more information, head over to the Quickstart.
Parameters: |
|
---|
Raises an HTTPException for the given status code. For example to abort request handling with a page not found exception, you would call abort(404).
Parameters: |
|
---|
Return a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, and 307. 300 is not supported because it’s not a real redirect and 304 because it’s the answer for a request with a request with defined If-Modified-Since headers.
New in version 0.6: The location can now be a unicode string that is encoded using the iri_to_uri() function.
Parameters: |
|
---|
Sends the contents of a file to the client. This will use the most efficient method available and configured. By default it will try to use the WSGI server’s file_wrapper support. Alternatively you can set the application’s use_x_sendfile attribute to True to directly emit an X-Sendfile header. This however requires support of the underlying webserver for X-Sendfile.
By default it will try to guess the mimetype for you, but you can also explicitly provide one. For extra security you probably want to sent certain files as attachment (HTML for instance).
Please never pass filenames to this function from user sources without checking them first. Something like this is usually sufficient to avoid security problems:
if '..' in filename or filename.startswith('/'):
abort(404)
New in version 0.2.
Parameters: |
|
---|
Marks a string as being safe for inclusion in HTML/XML output without needing to be escaped. This implements the __html__ interface a couple of frameworks and web applications use. Markup is a direct subclass of unicode and provides all the methods of unicode just that it escapes arguments passed and always returns Markup.
The escape function returns markup objects so that double escaping can’t happen. If you want to use autoescaping in Jinja just enable the autoescaping feature in the environment.
The constructor of the Markup class can be used for three different things: When passed an unicode object it’s assumed to be safe, when passed an object with an HTML representation (has an __html__ method) that representation is used, otherwise the object passed is converted into a unicode string and then assumed to be safe:
>>> Markup("Hello <em>World</em>!")
Markup(u'Hello <em>World</em>!')
>>> class Foo(object):
... def __html__(self):
... return '<a href="#">foo</a>'
...
>>> Markup(Foo())
Markup(u'<a href="#">foo</a>')
If you want object passed being always treated as unsafe you can use the escape() classmethod to create a Markup object:
>>> Markup.escape("Hello <em>World</em>!")
Markup(u'Hello <em>World</em>!')
Operations on a markup string are markup aware which means that all arguments are passed through the escape() function:
>>> em = Markup("<em>%s</em>")
>>> em % "foo & bar"
Markup(u'<em>foo & bar</em>')
>>> strong = Markup("<strong>%(text)s</strong>")
>>> strong % {'text': '<blink>hacker here</blink>'}
Markup(u'<strong><blink>hacker here</blink></strong>')
>>> Markup("<em>Hello</em> ") + "<foo>"
Markup(u'<em>Hello</em> <foo>')
Unescape markup again into an unicode string. This also resolves known HTML4 and XHTML entities:
>>> Markup("Main » <em>About</em>").unescape()
u'Main \xbb <em>About</em>'
Unescape markup into an unicode string and strip all tags. This also resolves known HTML4 and XHTML entities. Whitespace is normalized to one:
>>> Markup("Main » <em>About</em>").striptags()
u'Main \xbb About'
Flashes a message to the next request. In order to remove the flashed message from the session and to display it to the user, the template has to call get_flashed_messages().
Parameters: |
|
---|
Pulls all flashed messages from the session and returns them. Further calls in the same request to the function will return the same messages. By default just the messages are returned, but when with_categories is set to True, the return value will be a list of tuples in the form (category, message) instead.
Example usage:
{% for category, msg in get_flashed_messages(with_categories=true) %}
<p class=flash-{{ category }}>{{ msg }}
{% endfor %}
Changed in version 0.3: with_categories parameter added.
Parameters: |
|
---|
Creates a Response with the JSON representation of the given arguments with an application/json mimetype. The arguments to this function are the same as to the dict constructor.
Example usage:
@app.route('/_get_current_user')
def get_current_user():
return jsonify(username=g.user.username,
email=g.user.email,
id=g.user.id)
This will send a JSON response like this to the browser:
{
"username": "admin",
"email": "admin@localhost",
"id": 42
}
This requires Python 2.6 or an installed version of simplejson.
New in version 0.2.
If JSON support is picked up, this will be the module that Flask is using to parse and serialize JSON. So instead of doing this yourself:
try:
import simplejson as json
except ImportError:
import json
You can instead just do this:
from flask import json
For usage examples, read the json documentation.
The dumps() function of this json module is also available as filter called |tojson in Jinja2. Note that inside script tags no escaping must take place, so make sure to disable escaping with |safe if you intend to use it inside script tags:
<script type=text/javascript>
doSomethingWith({{ user.username|tojson|safe }});
</script>
Note that the |tojson filter escapes forward slashes properly.
Renders a template from the template folder with the given context.
Parameters: |
|
---|
Renders a template from the given template source string with the given context.
Parameters: |
|
---|
Loads a macro (or variable) a template exports. This can be used to invoke a macro from within Python code. If you for example have a template named _foo.html with the following contents:
{% macro hello(name) %}Hello {{ name }}!{% endmacro %}
You can access this from Python code like this:
hello = get_template_attribute('_foo.html', 'hello')
return hello('World')
New in version 0.2.
Parameters: |
|
---|
Works exactly like a dict but provides ways to fill it from files or special dictionaries. There are two common patterns to populate the config.
Either you can fill the config from a config file:
app.config.from_pyfile('yourconfig.cfg')
Or alternatively you can define the configuration options in the module that calls from_object() or provide an import path to a module that should be loaded. It is also possible to tell it to use the same module and with that provide the configuration values just before the call:
DEBUG = True
SECRET_KEY = 'development key'
app.config.from_object(__name__)
In both cases (loading from any Python file or loading from modules), only uppercase keys are added to the config. This makes it possible to use lowercase values in the config file for temporary values that are not added to the config or to define the config keys in the same file that implements the application.
Probably the most interesting way to load configurations is from an environment variable pointing to a file:
app.config.from_envvar('YOURAPPLICATION_SETTINGS')
In this case before launching the application you have to set this environment variable to the file you want to use. On Linux and OS X use the export statement:
export YOURAPPLICATION_SETTINGS='/path/to/config/file'
On windows use set instead.
Parameters: |
|
---|
Loads a configuration from an environment variable pointing to a configuration file. This basically is just a shortcut with nicer error messages for this line of code:
app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])
Parameters: |
|
---|---|
Returns: | bool. True if able to load config, False otherwise. |
Updates the values from the given object. An object can be of one of the following two types:
Objects are usually either modules or classes.
Just the uppercase variables in that object are stored in the config after lowercasing. Example usage:
app.config.from_object('yourapplication.default_config')
from yourapplication import default_config
app.config.from_object(default_config)
You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with from_pyfile() and ideally from a location not within the package because the package might be installed system wide.
Parameters: |
|
---|
Updates the values in the config from a Python file. This function behaves as if the file was imported as module with the from_object() function.
Parameters: |
|
---|