API

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.

Application Object

class flask.Flask(package_name)

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__)
add_url_rule(rule, endpoint, **options)

Connects a URL rule. Works exactly like the route() decorator but does not register the view function for the endpoint.

Basically this example:

@app.route('/')
def index():
    pass

Is equivalent to the following:

def index():
    pass
app.add_url_rule('index', '/')
app.view_functions['index'] = index
Parameters:
  • rule – the URL rule as string
  • endpoint – the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint
  • options – the options to be forwarded to the underlying Rule object
after_request(f)

Register a function to be run after each request.

after_request_funcs = None

a list of functions that are called at the end of the request. Tha function is passed the current response object and modify it in place or replace it. To register a function here use the after_request() decorator.

before_request(f)

Registers a function to run before each request.

before_request_funcs = None

a list of functions that should be called at the beginning of the request before request dispatching kicks in. This can for example be used to open database connections or getting hold of the currently logged in user. To register a function here, use the before_request() decorator.

context_processor(f)

Registers a template context processor function.

create_jinja_loader()

Creates the Jinja loader. By default just a package loader for the configured package is returned that looks up templates in the templates folder. To add other loaders it’s possible to override this method.

debug = None

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.

dispatch_request()

Does the request dispatching. Matches the URL and returns the return value of the view or error handler. This does not have to be a response object. In order to convert the return value to a proper response object, call make_response().

error_handlers = None

a dictionary of all registered error handlers. The key is be the error code as integer, the value the function that should handle that error. To register a error handler, use the errorhandler() decorator.

errorhandler(code)

A decorator that is used to register a function give a given error code. Example:

@app.errorhandler(404)
def page_not_found():
    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():
    return 'This page does not exist', 404
app.error_handlers[404] = page_not_found
Parameters:code – the code as integer for the handler
jinja_env = None

the Jinja2 environment. It is created from the jinja_options and the loader that is returned by the create_jinja_loader() function.

jinja_options = {'autoescape': True, 'extensions': ['jinja2.ext.autoescape', 'jinja2.ext.with_']}

options that are passed directly to the Jinja2 environment

make_response(rv)

Converts the return value from a view function to a real response object that is an instance of response_class.

The following types are allowd 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:rv – the return value from the view function
match_request()

Matches the current request against the URL map and also stores the endpoint and view arguments on the request object is successful, otherwise the exception is stored.

open_resource(resource)

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:resource – the name of the resource. To access resources within subfolders use forward slashes as separator.
open_session(request)

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:request – an instance of request_class.
package_name = None

the name of the package or module. Do not change this once it was set by the constructor.

preprocess_request()

Called before the actual request dispatching and will call every as before_request() decorated function. If any of these function returns a value it’s handled as if it was the return value from the view and further request handling is stopped.

process_response(response)

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:response – a response_class object.
Returns:a new response object or the same, has to be an instance of response_class.
request_class

the class that is used for request objects. See request for more information.

alias of Request

request_context(environ)

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)
Params environ:a WSGI environment
response_class

the class that is used for response objects. See Response for more information.

alias of Response

root_path = None

where is the app root located?

route(rule, **options)

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:

  1. If a rule ends with a slash and is requested without a slash by the user, the user is automatically redirected to the same page with a trailing slash attached.
  2. If a rule does not end with a trailing slash and the user request the page with a trailing slash, a 404 not found is raised.

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:
  • rule – the URL rule as string
  • methods – a list of methods this rule should be limited to (GET, POST etc.). By default a rule just listens for GET (and implicitly HEAD).
  • subdomain – specifies the rule for the subdoain in case subdomain matching is in use.
  • strict_slashes – can be used to disable the strict slashes setting for this rule. See above.
  • options – other options to be forwarded to the underlying Rule object.
run(host='localhost', port=5000, **options)

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:
  • host – the hostname to listen on. set this to '0.0.0.0' to have the server available externally as well.
  • port – the port of the webserver
  • options – the options to be forwarded to the underlying Werkzeug server. See werkzeug.run_simple() for more information.
save_session(session, response)

Saves the session if it needs updates. For the default implementation, check open_session().

Parameters:
  • session – the session to be saved (a SecureCookie object)
  • response – an instance of response_class
secret_key = None

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.

The secure cookie uses this for the name of the session cookie

static_path = '/static'

path for the static files. If you don’t want to use static files you can set this value to None in which case no URL rule is added and the development server will no longer serve any static files.

template_context_processors = None

a list of functions that are called without arguments to populate the template context. Each returns a dictionary that the template context is updated with. To register a function here, use the context_processor() decorator.

test_client()

Creates a test client for this application. For information about unit testing head over to Testing Flask Applications.

test_request_context(*args, **kwargs)

Creates a WSGI environment from the given values (see werkzeug.create_environ() for more information, this function accepts the same arguments).

update_template_context(context)

Update the template context with some commonly used variables. This injects request, session and g into the template context.

Parameters:context – the context as a dictionary that is updated in place to add extra variables.
view_functions = None

a dictionary of all view functions registered. The keys will be function names which are also used to generate URLs and the values are the function objects themselves. to register a view function, use the route() decorator.

wsgi_app(environ, start_response)

The actual WSGI application. This is not implemented in __call__ so that middlewares can be applied:

app.wsgi_app = MyMiddleware(app.wsgi_app)
Parameters:
  • environ – a WSGI environment
  • start_response – a callable accepting a status code, a list of headers and an optional exception context to start the response

Incoming Request Data

class flask.Request(environ)

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.

class flask.request

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.

form

A MultiDict with the parsed form data from POST or PUT requests. Please keep in mind that file uploads will not end up here, but instead in the files attribute.

args

A MultiDict with the parsed contents of the query string. (The part in the URL after the question mark).

values

A CombinedMultiDict with the contents of both form and args.

cookies

A dict with the contents of all cookies transmitted with the request.

stream

If the incoming form data was not encoded with a known encoding (for example it was transmitted as JSON) the data is stored unmodified in this stream for consumption. For example to read the incoming request data as JSON, one can do the following:

json_body = simplejson.load(request.stream)
files

A MultiDict with files uploaded as part of a POST or PUT request. Each file is stored as FileStorage object. It basically behaves like a standard file object you know from Python, with the difference that it also has a save() function that can store the file on the filesystem.

environ

The underlying WSGI environment.

method

The current request method (POST, GET etc.)

path
script_root
url
base_url
url_root

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
url http://www.example.com/myapplication/page.html
base_url http://www.example.com/myapplication/page.html?x=y
root_url http://www.example.com/myapplication/

Response Objects

class flask.Response(response=None, status=None, headers=None, mimetype=None, content_type=None, direct_passthrough=False)

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 request_class to your subclass.

headers

A Headers object representing the response headers.

status_code

The response status as integer.

data

A descriptor that calls get_data() and set_data(). This should not be used and will eventually get deprecated.

mimetype

The mimetype (content type without charset etc.)

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:
  • key – the key (name) of the cookie to be set.
  • value – the value of the cookie.
  • max_age – should be a number of seconds, or None (default) if the cookie should last only as long as the client’s browser session.
  • expires – should be a datetime object or UNIX timestamp.
  • domain – if you want to set a cross-domain cookie. For example, domain=".example.com" will set a cookie that is readable by the domain www.example.com, foo.example.com etc. Otherwise, a cookie will only be readable by the domain that set it.
  • path – limits the cookie to a given path, per default it will span the whole domain.

Sessions

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:

class flask.session

The session object works pretty much like an ordinary dict, with the difference that it keeps track on modifications.

The following attributes are interesting:

new

True if the session is new, False otherwise.

modified

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

Application Globals

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.

flask.g

Just store on this whatever you want. For example a database connection or the user that is currently logged in.

Useful Functions and Classes

flask.url_for(endpoint, **values)

Generates a URL to the given endpoint with the method provided.

Parameters:
  • endpoint – the endpoint of the URL (name of the function)
  • values – the variable arguments of the URL rule
flask.abort(code)

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:code – the HTTP error code.
flask.redirect(location, code=302, Response=None)

Returns 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.

New in version 0.10: The class used for the Response object can now be passed in.

Parameters:
  • location – the location the response should redirect to.
  • code – the redirect status code. defaults to 302.
  • Response (class) – a Response class to use when instantiating a response. The default is werkzeug.wrappers.Response if unspecified.
flask.escape(s) → markup

Convert the characters &, <, >, ‘, and ” in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. Marks return value as markup string.

class flask.Markup

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.

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 &lt;em&gt;World&lt;/em&gt;!')

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 &amp; bar</em>')
>>> strong = Markup("<strong>%(text)s</strong>")
>>> strong % {'text': '<blink>hacker here</blink>'}
Markup(u'<strong>&lt;blink&gt;hacker here&lt;/blink&gt;</strong>')
>>> Markup("<em>Hello</em> ") + "<foo>"
Markup(u'<em>Hello</em> &lt;foo&gt;')
classmethod escape(s)

Escape the string. Works like escape() with the difference that for subclasses of Markup this function would return the correct subclass.

striptags()

Unescape markup into an text_type string and strip all tags. This also resolves known HTML4 and XHTML entities. Whitespace is normalized to one:

>>> Markup("Main &raquo;  <em>About</em>").striptags()
u'Main \xbb About'
unescape()

Unescape markup again into an text_type string. This also resolves known HTML4 and XHTML entities:

>>> Markup("Main &raquo; <em>About</em>").unescape()
u'Main \xbb <em>About</em>'

Message Flashing

flask.flash(message)

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:message – the message to be flashed.
flask.get_flashed_messages()

Pulls all flashed messages from the session and returns them. Further calls in the same request to the function will return the same messages.

Template Rendering

flask.render_template(template_name, **context)

Renders a template from the template folder with the given context.

Parameters:
  • template_name – the name of the template to be rendered
  • context – the variables that should be available in the context of the template.
flask.render_template_string(source, **context)

Renders a template from the given template source string with the given context.

Parameters:
  • template_name – the sourcecode of the template to be rendered
  • context – the variables that should be available in the context of the template.