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__)
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: |
|
---|
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.
Changed in version 0.6: OPTIONS is added automatically as method.
Parameters: |
|
---|
Register a function to be run after each request.
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.
Registers a function to run before each request.
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.
The configuration dictionary as Config. This behaves exactly like a regular dictionary but supports additional methods to load a config from files.
Registers a template context processor function.
Creates the Jinja2 environment based on jinja_options and select_jinja_autoescape().
New in version 0.5.
Creates a URL adapter for the given request. The URL adapter is created at a point where the request context is not yet set up so the request is passed explicitly.
New in version 0.6.
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.
Default configuration parameters.
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().
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.
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 |
---|
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.
Handles an HTTP exception. By default this will invoke the registered error handlers and fall back to returning the exception as response.
This is True if the package bound object’s container has a folder named 'static'.
New in version 0.5.
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.
The Jinja2 environment. It is created from the jinja_options.
The Jinja loader for this package bound object.
New in version 0.5.
Options that are passed directly to the Jinja2 environment.
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.
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.
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 |
---|
all the loaded modules in a dictionary by name.
New in version 0.5.
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. |
---|
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. |
---|
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)
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.
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.
Changed in version 0.5: As of Flask 0.5 the functions registered for after request execution are called in reverse order of registration.
Parameters: | response – a response_class object. |
---|---|
Returns: | a new response object or the same, has to be an instance of response_class. |
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.
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 |
---|
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.
If you want to run the application in debug mode, but disable the code execution on the interactive debugger, you can pass use_evalex=False as parameter. This will keep the debugger’s traceback screen active, but disable code execution.
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: |
|
---|
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.
Returns True if autoescaping should be active for the given template name.
New in version 0.5.
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'
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.
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.
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. |
---|
Creates a test client for this application. For information about unit testing head over to Testing Flask Applications.
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.
Creates a WSGI environment from the given values (see werkzeug.create_environ() for more information, this function accepts the same arguments).
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 the template context with some commonly used variables. This injects request, session, config and g into the template context as well as everything template context processors want to inject. Note that the as of Flask 0.6, the original values in the context will not be overriden if a context processor decides to return a value with the same key.
Parameters: | context – the context as a dictionary that is updated in place to add extra variables. |
---|
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.
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.
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: |
|
---|
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.
New in version 0.6: The subdomain parameter was added.
Parameters: |
|
---|
Like Flask.add_url_rule() but for a module. The endpoint for the url_for() function is prefixed with the name of the module.
Changed in version 0.6: The endpoint argument is now optional and will default to the function name to consistent with the function of the same name on the application object.
Like Flask.after_request() but for a module. Such a function is executed after each request, even if outside of the module.
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.
Like Flask.context_processor() but for a module. Such a function is executed each request, even if outside of the module.
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.
Like Flask.before_request(). Such a function is executed before each request, even if outside of a module.
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.
Like Flask.context_processor() but for a module. This function is only executed for requests handled by a module.
This is True if the package bound object’s container has a folder named 'static'.
New in version 0.5.
The Jinja loader for this package bound object.
New in version 0.5.
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. |
---|
Like Flask.route() but for a module. The endpoint for the url_for() function is prefixed with the name of the module.
Function used internally to send static files from the static folder to the browser.
New in version 0.5.
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.
This is a proxy. See Notes On Proxies for more information.
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.
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.
A MultiDict with the parsed contents of the query string. (The part in the URL after the question mark).
A dict with the contents of all cookies transmitted with the request.
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.
Contains the incoming request data as string in case it came with a mimetype Flask does not handle.
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.
The underlying WSGI environment.
The current request method (POST, GET etc.)
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/ |
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.
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.
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.
A Headers object representing the response headers.
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: |
|
---|
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.
The mimetype (content type without charset etc.)
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.
This is a proxy. See Notes On Proxies for more information.
The following attributes are interesting:
True if the session is new, False otherwise.
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
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.
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.
Just store on this whatever you want. For example a database connection or the user that is currently logged in.
This is a proxy. See Notes On Proxies for more information.
Points to the application handling the request. This is useful for extensions that want to support multiple applications running side by side.
This is a proxy. See Notes On Proxies for more information.
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: | code – the HTTP error code. |
---|
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: |
|
---|
Sometimes it is necessary to set additional headers in a view. Because views do not have to return response objects but can return a value that is converted into a response object by Flask itself, it becomes tricky to add headers to it. This function can be called instead of using a return and you will get a response object which you can use to attach headers.
If view looked like this and you want to add a new header:
def index():
return render_template('index.html', foo=42)
You can now do something like this:
def index():
response = make_response(render_template('index.html', foo=42))
response.headers['X-Parachutes'] = 'parachutes are cool'
return response
This function accepts the very same arguments you can return from a view function. This for example creates a response with a 404 error code:
response = make_response(render_template('not_found.html'), 404)
Internally this function does the following things:
New in version 0.6.
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: |
|
---|
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: |
|
---|
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.
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 <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>')
Escape the string. Works like escape() with the difference that for subclasses of Markup this function would return the correct subclass.
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: | with_categories – set to True to also receive categories. |
---|
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.
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 _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: |
|
---|
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: | obj – an import name or object |
---|
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. |
---|
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:
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.
New in version 0.6.
True if the signalling system is available. This is the case when blinker is installed.
This signal is sent when a template was successfully rendered. The signal is invoked with the instance of the template as template and the context as dictionary (named context).
This signal is sent before any request processing started but when the request context was set up. Because the request context is already bound, the subscriber can access the request with the standard global proxies such as request.
This signal is sent right before the response is sent to the client. It is passed the response to be sent named response.
This signal is sent when an exception happens during request processing. It is sent before the standard exception handling kicks in and even in debug mode, where no exception handling happens. The exception itself is passed to the subscriber as exception.
An alias for blinker.base.Namespace if blinker is available, otherwise a dummy class that creates fake signals. This class is available for Flask extensions that want to provide the same fallback system as Flask itself.
Creates a new signal for this namespace if blinker is available, otherwise returns a fake signal that has a send method that will do nothing but will fail with a RuntimeError for all other operations, including connecting.
Some of the objects provided by Flask are proxies to other objects. The reason behind this is, that these proxies are shared between threads and they have to dispatch to the actual object bound to a thread behind the scenes as necessary.
Most of the time you don’t have to care about that, but there are some exceptions where it is good to know that this object is an actual proxy:
If you need to get access to the underlying object that is proxied, you can use the _get_current_object() method:
app = current_app._get_current_object()
my_signal.send(app)