API — Flask Documentation (0.12.x)
source link: https://flask.palletsprojects.com/en/0.12.x/api/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Application Object¶
class flask.
Flask
(import_name, static_path=None, static_url_path=None, static_folder='static', template_folder='templates', instance_path=None, instance_relative_config=False, root_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 of what belongs to your application. This name is used to find resources on the filesystem, 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 yourapplication.app and not yourapplication.views.frontend)
ChangelogParameters
import_name – the name of the application package
static_url_path – can be used to specify a different path for the static files on the web. Defaults to the name of the static_folder folder.
static_folder – the folder with static files that should be served at static_url_path. Defaults to the
'static'
folder in the root path of the application.template_folder – the folder that contains the templates that should be used by the application. Defaults to
'templates'
folder in the root path of the application.instance_path – An alternative instance path for the application. By default the folder
'instance'
next to the package or module is assumed to be the instance path.instance_relative_config – if set to
True
relative filenames for loading the config are assumed to be relative to the instance path instead of the application root.root_path – Flask by default will automatically calculate the path to the root of the application. In certain situations this cannot be achieved (for instance if the package is a Python 3 namespace package) and needs to be manually defined.
add_template_filter
(f, name=None)¶
Register a custom template filter. Works exactly like the
template_filter()
decorator.
name – the optional name of the filter, otherwise the function name will be used.
add_template_global
(f, name=None)¶
Register a custom template global function. Works exactly like the
template_global()
decorator.
ChangelogParameters
name – the optional name of the global function, otherwise the function name will be used.
add_template_test
(f, name=None)¶
Register a custom template test. Works exactly like the
template_test()
decorator.
ChangelogParameters
name – the optional name of the test, otherwise the function name will be used.
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
Internally route()
invokes add_url_rule()
so if you want
to customize the behavior via subclassing you only need to change
this method.
For more information refer to URL Route Registrations.
ChangelogParameters
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. A change to Werkzeug is handling of method options. methods is a list of methods this rule should be limited to (GET
,POST
etc.). By default a rule just listens forGET
(and implicitlyHEAD
). Starting with Flask 0.6,OPTIONS
is implicitly added and handled by the standard request handling.
after_request
(f)¶
Register a function to be run after each request.
Your function must take one parameter, an instance of
response_class
and return a new response object or the
same (see process_response()
).
As of Flask 0.7 this function might not be executed at the end of the request in case an unhandled exception occurred.
after_request_funcs
= None¶
A dictionary with lists of functions that should be called after
each request. The key of the dictionary is the name of the blueprint
this function is active for, None
for all requests. This can for
example be used to close database connections. To register a function
here, use the after_request()
decorator.
app_context
()¶
Binds the application only. For as long as the application is bound
to the current context the flask.current_app
points to that
application. An application context is automatically created when a
request context is pushed if necessary.
Example usage:
with app.app_context(): ...
Changelog
app_ctx_globals_class
¶
alias of flask.ctx._AppCtxGlobals
auto_find_instance_path
()¶
Tries to locate the instance path if it was not provided to the
constructor of the application class. It will basically calculate
the path to a folder named instance
next to your main file or
the package.
Changelog
before_first_request
(f)¶
Registers a function to be run before the first request to this instance of the application.
The function will be called without any arguments and its return value is ignored.
Changelog
before_first_request_funcs
= None¶
A lists of functions that should be called at the beginning of the
first request to this instance. To register a function here, use
the before_first_request()
decorator.
Changelog
before_request
(f)¶
Registers a function to run before each request.
The function will be called without any arguments. If the function returns a non-None value, it’s handled as if it was the return value from the view and further request handling is stopped.
before_request_funcs
= None¶
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 blueprint 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.
blueprints
= None¶
all the attached blueprints in a dictionary by name. Blueprints can be attached multiple times so this dictionary does not tell you how often they got attached.
Changelog
cli
= None¶
The click command line context for this application. Commands registered here show up in the flask command once the application has been discovered. The default commands are provided by Flask itself and can be overridden.
This is an instance of a click.Group
object.
config
= None¶
The configuration dictionary as Config
. This behaves
exactly like a regular dictionary but supports additional methods
to load a config from files.
config_class
¶
alias of flask.config.Config
context_processor
(f)¶
Registers a template context processor function.
create_global_jinja_loader
()¶
Creates the loader for the Jinja2 environment. Can be used to
override just the loader and keeping the rest unchanged. It’s
discouraged to override this function. Instead one should override
the jinja_loader()
function instead.
The global loader dispatches between the loaders of the application and the individual blueprints.
Changelog
create_jinja_environment
()¶
Creates the Jinja2 environment based on jinja_options
and select_jinja_autoescape()
. Since 0.7 this also adds
the Jinja2 globals and filters after initialization. Override
this function to customize the behavior.
Changelog
create_url_adapter
(request)¶
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.
Changelog
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 occurs 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
.
default_config
= {'APPLICATION_ROOT': None, 'DEBUG': False, 'EXPLAIN_TEMPLATE_LOADING': False, 'JSONIFY_MIMETYPE': 'application/json', 'JSONIFY_PRETTYPRINT_REGULAR': True, 'JSON_AS_ASCII': True, 'JSON_SORT_KEYS': True, 'LOGGER_HANDLER_POLICY': 'always', 'LOGGER_NAME': None, 'MAX_CONTENT_LENGTH': None, 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(days=31), 'PREFERRED_URL_SCHEME': 'http', 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'PROPAGATE_EXCEPTIONS': None, 'SECRET_KEY': None, 'SEND_FILE_MAX_AGE_DEFAULT': datetime.timedelta(seconds=43200), 'SERVER_NAME': None, 'SESSION_COOKIE_DOMAIN': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_SECURE': False, 'SESSION_REFRESH_EACH_REQUEST': True, 'TEMPLATES_AUTO_RELOAD': None, 'TESTING': False, 'TRAP_BAD_REQUEST_ERRORS': False, 'TRAP_HTTP_EXCEPTIONS': False, 'USE_X_SENDFILE': False}¶
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()
.
Changelog
do_teardown_appcontext
(exc=<object object>)¶
Called when an application context is popped. This works pretty
much the same as do_teardown_request()
but for the application
context.
Changelog
do_teardown_request
(exc=<object object>)¶
Called after the actual request dispatching and will
call every as teardown_request()
decorated function. This is
not actually called by the Flask
object itself but is always
triggered when the request context is popped. That way we have a
tighter control over certain resources under testing environments.
Changelog
endpoint
(endpoint)¶
A decorator to register a function as an endpoint. Example:
@app.endpoint('example.endpoint') def example(): return "example"
endpoint – the name of the endpoint
error_handler_spec
= None¶
A dictionary of all registered error handlers. The key is None
for error handlers active on the application, otherwise the key is
the name of the blueprint. Each key points to another dictionary
where the key is the status code of the http exception. The
special key None
points to a list of tuples where the first item
is the class for the instance check and the second the error handler
function.
To register a error handler, use the errorhandler()
decorator.
errorhandler
(code_or_exception)¶
A decorator that is used to register a function given an error code. Example:
@app.errorhandler(404) def page_not_found(error): return 'This page does not exist', 404
You can also register handlers for arbitrary exceptions:
@app.errorhandler(DatabaseError) def special_exception_handler(error): return 'Database connection failed', 500
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_handler_spec[None][404] = page_not_found
Setting error handlers via assignments to error_handler_spec
however is discouraged as it requires fiddling with nested dictionaries
and the special case for arbitrary exception types.
The first None
refers to the active blueprint. If the error
handler should be application wide None
shall be used.
ChangelogParameters
code_or_exception – the code as integer for the handler, or an arbitrary exception
extensions
= None¶
a place where extensions can store application specific state. For example this is where an extension could store database engines and similar things. For backwards compatibility extensions should register themselves like this:
if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['extensionname'] = SomeObject()
The key must match the name of the extension module. For example in
case of a “Flask-Foo” extension in flask_foo, the key would be
'foo'
.
Changelog
full_dispatch_request
()¶
Dispatches the request and on top of that performs request pre and postprocessing as well as HTTP exception catching and error handling.
Changelog
get_send_file_max_age
(filename)¶
Provides default cache_timeout for the send_file()
functions.
By default, this function returns SEND_FILE_MAX_AGE_DEFAULT
from
the configuration of current_app
.
Static file functions such as send_from_directory()
use this
function, and send_file()
calls this function on
current_app
when the given cache_timeout is None
. If a
cache_timeout is given in send_file()
, that timeout is used;
otherwise, this method is called.
This allows subclasses to change the behavior when sending files based on the filename. For example, to set the cache timeout for .js files to 60 seconds:
class MyFlask(flask.Flask): def get_send_file_max_age(self, name): if name.lower().endswith('.js'): return 60 return flask.Flask.get_send_file_max_age(self, name)
Changelog
property got_first_request
¶
This attribute is set to True
if the application started
handling the first request.
Changelog
handle_exception
(e)¶
Default exception handling that kicks in when an exception occurs that is not caught. 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.
Changelog
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.
Changelog
handle_url_build_error
(error, endpoint, values)¶
Handle BuildError
on url_for()
.
handle_user_exception
(e)¶
This method is called whenever an exception occurs that should be
handled. A special case are
HTTPException
s which are forwarded by
this function to the handle_http_exception()
method. This
function will either return a response value or reraise the
exception with the same traceback.
Changelog
property has_static_folder
¶
This is True
if the package bound object’s container has a
folder for static files.
Changelog
init_jinja_globals
()¶
Deprecated. Used to initialize the Jinja2 globals.
Changelog
inject_url_defaults
(endpoint, values)¶
Injects the URL defaults for the given endpoint directly into the values dictionary passed. This is used internally and automatically called on URL building.
Changelog
instance_path
= None¶
Holds the path to the instance folder.
Changelog
iter_blueprints
()¶
Iterates over all blueprints by the order they were registered.
Changelog
jinja_env
¶
The Jinja2 environment used to load templates.
jinja_environment
¶
alias of flask.templating.Environment
jinja_loader
¶
The Jinja loader for this package bound object.
Changelog
jinja_options
= {'extensions': ['jinja2.ext.autoescape', 'jinja2.ext.with_']}¶
Options that are passed directly to the Jinja2 environment.
json_decoder
¶
alias of flask.json.JSONDecoder
json_encoder
¶
alias of flask.json.JSONEncoder
log_exception
(exc_info)¶
Logs an exception. This is called by handle_exception()
if debugging is disabled and right before the handler is called.
The default implementation logs the exception as error on the
logger
.
Changelog
property 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 occurred (%d apples)', 42) app.logger.error('An error occurred')
Changelog
logger_name
¶
The name of the logger to use. By default the logger name is the package name passed to the constructor.
Changelog
make_config
(instance_relative=False)¶
Used to create the config attribute by the Flask constructor. The instance_relative parameter is passed in from the constructor of Flask (there named instance_relative_config) and indicates if the config should be relative to the instance path or the root path of the application.
Changelog
make_default_options_response
()¶
This method is called to create the default OPTIONS
response.
This can be changed through subclassing to change the default
behavior of OPTIONS
responses.
Changelog
make_null_session
()¶
Creates a new instance of a missing session. Instead of overriding
this method we recommend replacing the session_interface
.
Changelog
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:
the object is returned unchanged
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
a WSGI function
the function is called as WSGI application and buffered as response object
A tuple in the form (response, status,
headers)
or (response, headers)
where response is any of the
types defined here, status is a string
or an integer and headers is a list or
a dictionary with header values.
rv – the return value from the view function
Changelog
make_shell_context
()¶
Returns the shell context for an interactive shell for this application. This runs all the registered shell context processors.
Changelog
name
¶
The name of the application. This is usually the import name with the difference that it’s guessed from the run file if the import name is main. This name is used as a display name when Flask needs the name of the application. It can be set and overridden to change the value.
Changelog
open_instance_resource
(resource, mode='rb')¶
Opens a resource from the application’s instance folder
(instance_path
). Otherwise works like
open_resource()
. Instance resources can also be opened for
writing.
resource – the name of the resource. To access resources within subfolders use forward slashes as separator.
mode – resource file opening mode, default is ‘rb’.
open_resource
(resource, mode='rb')¶
Opens a resource from the application’s resource folder. To see how this works, consider the following folder structure:
/myapplication.py /schema.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)
resource – the name of the resource. To access resources within subfolders use forward slashes as separator.
mode – resource file opening mode, default is ‘rb’.
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. Instead of overriding this method
we recommend replacing the session_interface
.
request – an instance of request_class
.
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 each before_request()
decorated function, passing no
arguments.
If any of these functions returns a value, it’s handled as
if it was the return value from the view and further
request handling is stopped.
This also triggers the url_value_preprocessor()
functions before
the actual before_request()
functions are called.
property preserve_context_on_exception
¶
Returns the value of the PRESERVE_CONTEXT_ON_EXCEPTION
configuration value in case it’s set, otherwise a sensible default
is returned.
Changelog
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.
ChangelogParameters
response – a response_class
object.
Returns
a new response object or the same, has to be an
instance of response_class
.
property propagate_exceptions
¶
Returns the value of the PROPAGATE_EXCEPTIONS
configuration
value in case it’s set, otherwise a sensible default is returned.
Changelog
register_blueprint
(blueprint, **options)¶
Registers a blueprint on the application.
Changelog
register_error_handler
(code_or_exception, f)¶
Alternative error attach function to the errorhandler()
decorator that is more straightforward to use for non decorator
usage.
Changelog
request_class
¶
alias of flask.wrappers.Request
request_context
(environ)¶
Creates a RequestContext
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()
ChangelogParameters
environ – a WSGI environment
response_class
¶
alias of flask.wrappers.Response
route
(rule, **options)¶
A decorator that is used to register a view function for a
given URL rule. This does the same thing as add_url_rule()
but is intended for decorator usage:
@app.route('/') def index(): return 'Hello World'
For more information refer to URL Route Registrations.
Parametersrule – 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. A change to Werkzeug is handling of method options. methods is a list of methods this rule should be limited to (GET
,POST
etc.). By default a rule just listens forGET
(and implicitlyHEAD
). Starting with Flask 0.6,OPTIONS
is implicitly added and handled by the standard request handling.
run
(host=None, port=None, debug=None, **options)¶
Runs the application on a local development server.
Do not use run()
in a production setting. It is not intended to
meet security and performance requirements for a production server.
Instead, see Deployment Options for WSGI server recommendations.
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.
It is not recommended to use this function for development with
automatic reloading as this is badly supported. Instead you should
be using the flask command line script’s run
support.
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.
ChangelogParameters
host – the hostname to listen on. Set this to
'0.0.0.0'
to have the server available externally as well. Defaults to'127.0.0.1'
.port – the port of the webserver. Defaults to
5000
or the port defined in theSERVER_NAME
config variable if present.debug – if given, enable or disable debug mode. See
debug
.options – the options to be forwarded to the underlying Werkzeug server. See
werkzeug.serving.run_simple()
for more information.
save_session
(session, response)¶
Saves the session if it needs updates. For the default
implementation, check open_session()
. Instead of overriding this
method we recommend replacing the session_interface
.
session – the session to be saved (a
SecureCookie
object)response – an instance of
response_class
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. If no template name is given, returns True.
Changelog
send_file_max_age_default
¶
A timedelta
which is used as default cache_timeout
for the send_file()
functions. The default is 12 hours.
This attribute can also be configured from the config with the
SEND_FILE_MAX_AGE_DEFAULT
configuration key. This configuration
variable can also be set with an integer value used as seconds.
Defaults to timedelta(hours=12)
send_static_file
(filename)¶
Function used internally to send static files from the static folder to the browser.
Changelog
session_cookie_name
¶
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'
session_interface
= <flask.sessions.SecureCookieSessionInterface object>¶
the session interface to use. By default an instance of
SecureCookieSessionInterface
is used here.
Changelog
shell_context_processor
(f)¶
Registers a shell context processor function.
Changelog
shell_context_processors
= None¶
A list of shell context processor functions that should be run when a shell context is created.
Changelog
should_ignore_error
(error)¶
This is called to figure out if an error should be ignored
or not as far as the teardown system is concerned. If this
function returns True
then the teardown handlers will not be
passed the error.
Changelog
property static_folder
¶
The absolute path to the configured static folder.
teardown_appcontext
(f)¶
Registers a function to be called when the application context ends. These functions are typically also called when the request context is popped.
Example:
ctx = app.app_context() ctx.push() ... ctx.pop()
When ctx.pop()
is executed in the above example, the teardown
functions are called just before the app context moves from the
stack of active contexts. This becomes relevant if you are using
such constructs in tests.
Since a request context typically also manages an application context it would also be called when you pop a request context.
When a teardown function was called because of an exception it will be passed an error object.
The return values of teardown functions are ignored.
Changelog
teardown_appcontext_funcs
= None¶
A list of functions that are called when the application context is destroyed. Since the application context is also torn down if the request ends this is the place to store code that disconnects from databases.
Changelog
teardown_request
(f)¶
Register a function to be run at the end of each request, regardless of whether there was an exception or not. These functions are executed when the request context is popped, even if not an actual request was performed.
Example:
ctx = app.test_request_context() ctx.push() ... ctx.pop()
When ctx.pop()
is executed in the above example, the teardown
functions are called just before the request context moves from the
stack of active contexts. This becomes relevant if you are using
such constructs in tests.
Generally teardown functions must take every necessary step to avoid that they will fail. If they do execute code that might fail they will have to surround the execution of these code by try/except statements and log occurring errors.
When a teardown function was called because of a exception it will be passed an error object.
The return values of teardown functions are ignored.
Debug Note
In debug mode Flask will not tear down a request on an exception
immediately. Instead it will keep it alive so that the interactive
debugger can still access it. This behavior can be controlled
by the PRESERVE_CONTEXT_ON_EXCEPTION
configuration variable.
teardown_request_funcs
= None¶
A dictionary with lists of functions that are called after
each request, even if an exception has occurred. The key of the
dictionary is the name of the blueprint this function is active for,
None
for all requests. These functions are not allowed to modify
the request, and their return values are ignored. If an exception
occurred while processing the request, it gets passed to each
teardown_request function. To register a function here, use the
teardown_request()
decorator.
Changelog
template_context_processors
= None¶
A dictionary with list of functions that are called without argument
to populate the template context. The key of the dictionary is the
name of the blueprint 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]
name – the optional name of the filter, otherwise the function name will be used.
template_global
(name=None)¶
A decorator that is used to register a custom template global function. You can specify a name for the global function, otherwise the function name will be used. Example:
@app.template_global() def double(n): return 2 * n
ChangelogParameters
name – the optional name of the global function, otherwise the function name will be used.
template_test
(name=None)¶
A decorator that is used to register custom template test. You can specify a name for the test, otherwise the function name will be used. Example:
@app.template_test() def is_prime(n): if n == 2: return True for i in range(2, int(math.ceil(math.sqrt(n))) + 1): if n % i == 0: return False return True
ChangelogParameters
name – the optional name of the test, otherwise the function name will be used.
test_client
(use_cookies=True, **kwargs)¶
Creates a test client for this application. For information about unit testing head over to Testing Flask Applications.
Note that if you are testing for assertions or exceptions in your
application code, you must set app.testing = True
in order for the
exceptions to propagate to the test client. Otherwise, the exception
will be handled by the application (not visible to the test client) and
the only indication of an AssertionError or other exception will be a
500 status code response to the test client. See the testing
attribute. For example:
app.testing = True client = app.test_client()
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'
Additionally, you may pass optional keyword arguments that will then
be passed to the application’s test_client_class
constructor.
For example:
from flask.testing import FlaskClient class CustomClient(FlaskClient): def __init__(self, *args, **kwargs): self._authentication = kwargs.pop("authentication") super(CustomClient,self).__init__( *args, **kwargs) app.test_client_class = CustomClient client = app.test_client(authentication='Basic ....')
See FlaskClient
for more information.
Changelog
test_client_class
= None¶
the test client that is used with when test_client is used.
Changelog
test_request_context
(*args, **kwargs)¶
Creates a WSGI environment from the given values (see
werkzeug.test.EnvironBuilder
for more information, this
function accepts the same arguments).
testing
¶
The testing flag. 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.
If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the default it’s implicitly enabled.
This attribute can also be configured from the config with the
TESTING
configuration key. Defaults to False
.
trap_http_exception
(e)¶
Checks if an HTTP exception should be trapped or not. By default
this will return False
for all exceptions except for a bad request
key error if TRAP_BAD_REQUEST_ERRORS
is set to True
. It
also returns True
if TRAP_HTTP_EXCEPTIONS
is set to True
.
This is called for all HTTP exceptions raised by a view function.
If it returns True
for any exception the error handler for this
exception is not called and it shows up as regular exception in the
traceback. This is helpful for debugging implicitly raised HTTP
exceptions.
Changelog
update_template_context
(context)¶
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 overridden if a context processor decides to return a value with the same key.
Parameterscontext – the context as a dictionary that is updated in place to add extra variables.
url_build_error_handlers
= None¶
A list of functions that are called when url_for()
raises a
BuildError
. Each function registered here
is called with error, endpoint and values. If a function
returns None
or raises a BuildError
the next function is
tried.
Changelog
url_default_functions
= None¶
A dictionary with lists of functions that can be used as URL value
preprocessors. The key None
here is used for application wide
callbacks, otherwise the key is the name of the blueprint.
Each of these functions has the chance to modify the dictionary
of URL values before they are used as the keyword arguments of the
view function. For each function registered this one should also
provide a url_defaults()
function that adds the parameters
automatically again that were removed that way.
Changelog
url_defaults
(f)¶
Callback function for URL defaults for all view functions of the application. It’s called with the endpoint and values and should update the values passed in place.
url_map
= None¶
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.routing import BaseConverter class ListConverter(BaseConverter): def to_python(self, value): return value.split(',') def to_url(self, values): return ','.join(super(ListConverter, self).to_url(value) for value in values) app = Flask(__name__) app.url_map.converters['list'] = ListConverter
url_rule_class
¶
alias of werkzeug.routing.Rule
url_value_preprocessor
(f)¶
Registers a function as URL value preprocessor for all view functions of the application. It’s called before the view functions are called and can modify the url values provided.
url_value_preprocessors
= None¶
A dictionary with lists of functions that can be used as URL
value processor functions. Whenever a URL is built these functions
are called to modify the dictionary of values in place. The key
None
here is used for application wide
callbacks, otherwise the key is the name of the blueprint.
Each of these functions has the chance to modify the dictionary
Changelog
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.
Changelog
This attribute can also be configured from the config with the
USE_X_SENDFILE
configuration key. Defaults to False
.
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 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.
ChangelogParameters
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
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK