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(import_name, static_path=None)

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__)

About the First Parameter

The idea of the first parameter is to give Flask an idea what belongs to your application. This name is used to find resources on the file system, can be used by extensions to improve debugging information and a lot more.

So it’s important what you provide there. If you are using a single module, __name__ is always the correct value. If you however are using a package, it’s usually recommended to hardcode the name of your package there.

For example if your application is defined in yourapplication/app.py you should create it with one of the two versions below:

app = Flask('yourapplication')
app = Flask(__name__.split('.')[0])

Why is that? The application will work even with __name__, thanks to how resources are looked up. However it will make debugging more painful. Certain extensions can make assumptions based on the import name of your application. For example the Flask-SQLAlchemy extension will look for the code in your application that triggered an SQL query in debug mode. If the import name is not properly set up, that debugging information is lost. (For example it would only pick up SQL queries in yourapplicaiton.app and not yourapplication.views.frontend)

New in version 0.5: The static_path parameter was added.

Parameters:
  • import_name – the name of the application package
  • static_path – can be used to specify a different path for the static files on the web. Defaults to /static. This does not affect the folder the files are served from.
add_url_rule(rule, endpoint=None, view_func=None, **options)

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:
  • 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
  • view_func – the function to call when serving a request to the provided 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

A dictionary with lists of functions that should be called after each request. The key of the dictionary is the name of the module this function is active for, None for all requests. 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.

before_request(f)

Registers a function to run before each request.

before_request_funcs

A dictionary with lists of functions that should be called at the beginning of the request. The key of the dictionary is the name of the module this function is active for, None for all requests. 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.

config

The configuration dictionary as Config. This behaves exactly like a regular dictionary but supports additional methods to load a config from files.

context_processor(f)

Registers a template context processor function.

create_jinja_environment()

Creates the Jinja2 environment based on jinja_options and create_jinja_loader().

New in version 0.5.

debug

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.

debug_log_format

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.

default_config

Default configuration parameters.

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

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(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:
  • code – the code as integer for the handler
handle_exception(e)

Default exception handling that kicks in when an exception occours that is not catched. In debug mode the exception will be re-raised immediately, otherwise it is logged and the handler for a 500 internal server error is used. If no such handler exists, a default 500 internal server error message is displayed.

handle_http_exception(e)

Handles an HTTP exception. By default this will invoke the registered error handlers and fall back to returning the exception as response.

has_static_folder

This is True if the package bound object’s container has a folder named 'static'.

New in version 0.5.

init_jinja_globals()

Called directly after the environment was created to inject some defaults (like url_for, get_flashed_messages and the tojson filter.

New in version 0.5.

jinja_env

The Jinja2 environment. It is created from the jinja_options.

jinja_loader

The Jinja loader for this package bound object.

New in version 0.5.

jinja_options

Options that are passed directly to the Jinja2 environment.

logger

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.

logger_name

The name of the logger to use. By default the logger name is the package name passed to the constructor.

New in version 0.4.

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 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:
  • rv – the return value from the view function
modules

all the loaded modules in a dictionary by name.

New in version 0.5.

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
/templates
    /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:
permanent_session_lifetime

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)

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

a new response object or the same, has to be an instance of response_class.

register_module(module, **options)

Registers a module with this application. The keyword argument of this function are the same as the ones for the constructor of the Module class and will override the values of the module if provided.

request_class

The class that is used for request objects. See Request for more information.

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)

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:
  • environ – a WSGI environment
response_class

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

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 subdomain 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='127.0.0.1', 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.

Keep in Mind

Flask will suppress any server error with a generic error page unless it is in debug mode. As such to enable just the interactive debugger without the code reloading, you have to invoke run() with debug=True and use_reloader=False. Setting use_debugger to True without being in debug mode won’t catch any exceptions because there won’t be any to catch.

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:
secret_key

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.

select_jinja_autoescape(filename)

Returns True if autoescaping should be active for the given template name.

New in version 0.5.

send_static_file(filename)

Function used internally to send static files from the static folder to the browser.

New in version 0.5.

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'

static_path

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.

This is the default used for application and modules unless a different value is passed to the constructor.

template_context_processors

A dictionary with list of functions that are called without argument to populate the template context. They key of the dictionary is the name of the module this function is active for, None for all requests. Each returns a dictionary that the template context is updated with. To register a function here, use the context_processor() decorator.

template_filter(name=None)

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:
  • name – the optional name of the filter, otherwise the function name will be used.
test_client()

Creates a test client for this application. For information about unit testing head over to Flaskアプリケーションのテスト.

The test client can be used in a with block to defer the closing down of the context until the end of the with block. This is useful if you want to access the context locals for testing:

with app.test_client() as c:
    rv = c.get('/?vodka=42')
    assert request.args['vodka'] == '42'

Changed in version 0.4: added support for with block usage for the client.

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

testing

The testing flask. Set this to True to enable the test mode of Flask extensions (and in the future probably also Flask itself). For example this might activate unittest helpers that have an additional runtime cost which should not be enabled by default.

This attribute can also be configured from the config with the TESTING configuration key. Defaults to False.

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

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
use_x_sendfile

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.

view_functions

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

Changed in version 0.4: The after_request() functions are now called even if an error handler took over request processing. This ensures that even if an exception happens database have the chance to properly close the connection.

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

Module Objects

class flask.Module(import_name, name=None, url_prefix=None, static_path=None)

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.

New in version 0.5: The static_path parameter was added and it’s now possible for modules to refer to their own templates and static files. See modules-and-resources for more information.

Parameters:
  • import_name – the name of the Python package or module implementing this Module.
  • name – the internal short name for the module. Unless specified the rightmost part of the import name
  • url_prefix – an optional string that is used to prefix all the URL rules of this module. This can also be specified when registering the module with the application.
  • static_path – can be used to specify a different path for the static files on the web. Defaults to /static. This does not affect the folder the files are served from.
add_url_rule(rule, endpoint, view_func=None, **options)

Like Flask.add_url_rule() but for a module. The endpoint for the url_for() function is prefixed with the name of the module.

after_app_request(f)

Like Flask.after_request() but for a module. Such a function is executed after each request, even if outside of the module.

after_request(f)

Like Flask.after_request() but for a module. This function is only executed after each request that is handled by a function of that module.

app_context_processor(f)

Like Flask.context_processor() but for a module. Such a function is executed each request, even if outside of the module.

app_errorhandler(code)

Like Flask.errorhandler() but for a module. This handler is used for all requests, even if outside of the module.

New in version 0.4.

before_app_request(f)

Like Flask.before_request(). Such a function is executed before each request, even if outside of a module.

before_request(f)

Like Flask.before_request() but for a module. This function is only executed before each request that is handled by a function of that module.

context_processor(f)

Like Flask.context_processor() but for a module. This function is only executed for requests handled by a module.

has_static_folder

This is True if the package bound object’s container has a folder named 'static'.

New in version 0.5.

jinja_loader

The Jinja loader for this package bound object.

New in version 0.5.

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
/templates
    /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.
route(rule, **options)

Like Flask.route() but for a module. The endpoint for the url_for() function is prefixed with the name of the module.

send_static_file(filename)

Function used internally to send static files from the static folder to the browser.

New in version 0.5.

Incoming Request Data

class flask.Request(environ, populate_request=True, shallow=False)

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 mimetype the data is stored unmodified in this stream for consumption. Most of the time it is a better idea to use data which will give you that data as a string. The stream only returns the data once.

data

Contains the incoming request data as string in case it came with a mimetype Flask does not handle.

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
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/
is_xhr

True if the request was triggered via a JavaScript XMLHttpRequest. This only works with libraries that support the X-Requested-With header and set it to XMLHttpRequest. Libraries that do that are prototype, jQuery and Mochikit and probably some more.

json

Contains the parsed body of the JSON request if the mimetype of the incoming data was application/json. This requires Python 2.6 or an installed version of simplejson.

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

headers

A Headers object representing the response headers.

status_code

The response status as integer.

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

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.

mimetype

The mimetype (content type without charset etc.)

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
permanent

If set to True the session life for permanent_session_lifetime seconds. The default is 31 days. If set to False (which is the default) the session will be deleted when the user closes the browser.

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

Points to the application handling the request. This is useful for extensions that want to support multiple applications running side by side.

flask.url_for(endpoint, **values)

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:
  • endpoint – the endpoint of the URL (name of the function)
  • values – the variable arguments of the URL rule
  • _external – if set to True, an absolute URL is generated.
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)

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:
  • location – the location the response should redirect to.
  • code – the redirect status code.
flask.send_file(filename_or_fp, mimetype=None, as_attachment=False, attachment_filename=None, add_etags=True, cache_timeout=43200, conditional=False)

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.

New in version 0.5: The add_etags, cache_timeout and conditional parameters were added. The default behaviour is now to attach etags.

Parameters:
  • filename_or_fp – the filename of the file to send. This is relative to the root_path if a relative path is specified. Alternatively a file object might be provided in which case X-Sendfile might not work and fall back to the traditional method.
  • mimetype – the mimetype of the file if provided, otherwise auto detection happens.
  • as_attachment – set to True if you want to send this file with a Content-Disposition: attachment header.
  • attachment_filename – the filename for the attachment if it differs from the file’s filename.
  • add_etags – set to False to disable attaching of etags.
  • conditional – set to True to enable conditional responses.
  • cache_timeout – the timeout in seconds for the headers.
flask.send_from_directory(directory, filename, **options)

Send a file from a given directory with send_file(). This is a secure way to quickly expose static files from an upload folder or something similar.

Example usage:

@app.route('/uploads/<path:filename>')
def download_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename, as_attachment=True)

Sending files and Performance

It is strongly recommended to activate either X-Sendfile support in your webserver or (if no authentication happens) to tell the webserver to serve files for the given path on its own without calling into the web application for improved performance.

New in version 0.5.

Parameters:
  • directory – the directory where all the files are stored.
  • filename – the filename relative to that directory to download.
  • options – optional keyword arguments that are directly forwarded to send_file().
flask.escape(s)

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

unescape()

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

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

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 &raquo;  <em>About</em>").striptags()
u'Main \xbb About'

Message Flashing

flask.flash(message, category='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.
  • category – the category for the message. The following values are recommended: 'message' for any kind of message, 'error' for errors, 'info' for information messages and 'warning' for warnings. However any kind of string can be used as category.
flask.get_flashed_messages(with_categories=False)

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:
  • with_categories – set to True to also receive categories.

Returning JSON

flask.jsonify(*args, **kwargs)

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. For security reasons only objects are supported toplevel. For more information about this, have a look at JSON Security.

New in version 0.2.

flask.json

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.

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.
flask.get_template_attribute(template_name, attribute)

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 _cider.html with the following contents:

{% macro hello(name) %}Hello {{ name }}!{% endmacro %}

You can access this from Python code like this:

hello = get_template_attribute('_cider.html', 'hello')
return hello('World')

New in version 0.2.

Parameters:
  • template_name – the name of the template
  • attribute – the name of the variable of macro to acccess

Configuration

class flask.Config(root_path, defaults=None)

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:
  • root_path – path to which files are read relative from. When the config object is created by the application, this is the application’s root_path.
  • defaults – an optional dictionary of default values
from_envvar(variable_name, silent=False)

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:
  • variable_name – name of the environment variable
  • silent – set to True if you want silent failing for missing files.
Returns:

bool. True if able to load config, False otherwise.

from_object(obj)

Updates the values from the given object. An object can be of one of the following two types:

  • a string: in this case the object with that name will be imported
  • an actual object reference: that object is used directly

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:
  • obj – an import name or object
from_pyfile(filename)

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:
  • filename – the filename of the config. This can either be an absolute filename or a filename relative to the root path.

Useful Internals

flask._request_ctx_stack

The internal LocalStack that is used to implement all the context local objects used in Flask. This is a documented instance and can be used by extensions and application code but the use is discouraged in general.

The following attributes are always present on each layer of the stack:

app
the active Flask application.
url_adapter
the URL adapter that was used to match the request.
request
the current request object.
session
the active session object.
g
an object with all the attributes of the flask.g object.
flashes
an internal cache for the flashed messages.

Example usage:

from flask import _request_ctx_stack

def get_session():
    ctx = _request_ctx_stack.top
    if ctx is not None:
        return ctx.session

Changed in version 0.4.

The request context is automatically popped at the end of the request for you. In debug mode the request context is kept around if exceptions happen so that interactive debuggers have a chance to introspect the data. With 0.4 this can also be forced for requests that did not fail and outside of DEBUG mode. By setting 'flask._preserve_context' to True on the WSGI environment the context will not pop itself at the end of the request. This is used by the test_client() for example to implement the deferred cleanup functionality.

You might find this helpful for unittests where you need the information from the context local around for a little longer. Make sure to properly pop() the stack yourself in that situation, otherwise your unittests will leak memory.