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, static_url_path=None, static_folder='static', template_folder='templates', instance_path=None, instance_relative_config=False)¶ 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 yourapplication.app and not yourapplication.views.frontend)
New in version 0.7: The static_url_path, static_folder, and template_folder parameters were added.
New in version 0.8: The instance_path and instance_relative_config parameters were added.
Parameters: - 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.
-
add_template_filter
(*args, **kwargs)¶ Register a custom template filter. Works exactly like the
template_filter()
decorator.Parameters: name – the optional name of the filter, otherwise the function name will be used.
-
add_template_global
(*args, **kwargs)¶ Register a custom template global function. Works exactly like the
template_global()
decorator.New in version 0.10.
Parameters: name – the optional name of the global function, otherwise the function name will be used.
-
add_template_test
(*args, **kwargs)¶ Register a custom template test. Works exactly like the
template_test()
decorator.New in version 0.10.
Parameters: name – the optional name of the test, otherwise the function name will be used.
-
add_url_rule
(*args, **kwargs)¶ 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()
invokesadd_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.
Changed in version 0.2: view_func parameter added.
Changed in version 0.6: OPTIONS is added automatically as method.
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. 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 for GET (and implicitly HEAD). Starting with Flask 0.6, OPTIONS is implicitly added and handled by the standard request handling.
-
after_request
(*args, **kwargs)¶ Register a function to be run after each request. Your function must take one parameter, a
response_class
object and return a new response object or the same (seeprocess_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 open database connections or getting hold of the currently logged in user. 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(): ...
New in version 0.9.
-
app_ctx_globals_class
¶ The class that is used for the
g
instance.Example use cases for a custom class:
- Store arbitrary attributes on flask.g.
- Add a property for lazy per-request database connectors.
- Return None instead of AttributeError on expected attributes.
- Raise exception if an unexpected attr is set, a “controlled” flask.g.
In Flask 0.9 this property was called request_globals_class but it was changed in 0.10 to
app_ctx_globals_class
because the flask.g object is not application context scoped.New in version 0.10.
alias of
_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.New in version 0.8.
-
before_first_request
(*args, **kwargs)¶ Registers a function to be run before the first request to this instance of the application.
New in version 0.8.
-
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.New in version 0.8.
-
before_request
(*args, **kwargs)¶ Registers a function to run before each request.
-
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.
New in version 0.7.
-
config
= None¶ The configuration dictionary as
Config
. This behaves exactly like a regular dictionary but supports additional methods to load a config from files.
-
context_processor
(*args, **kwargs)¶ 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.
New in version 0.7.
-
create_jinja_environment
()¶ Creates the Jinja2 environment based on
jinja_options
andselect_jinja_autoescape()
. Since 0.7 this also adds the Jinja2 globals and filters after initialization. Override this function to customize the behavior.New in version 0.5.
-
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.
New in version 0.6.
Changed in version 0.9: This can now also be called without a request object when the URL adapter is created for the application context.
-
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.
-
debug_log_format
= '--------------------------------------------------------------------------------\n%(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n%(message)s\n--------------------------------------------------------------------------------'¶ 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
= ImmutableDict({'JSON_AS_ASCII': True, 'USE_X_SENDFILE': False, 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_DOMAIN': None, 'SESSION_COOKIE_NAME': 'session', 'LOGGER_NAME': None, 'DEBUG': False, 'SECRET_KEY': None, 'MAX_CONTENT_LENGTH': None, 'APPLICATION_ROOT': None, 'SERVER_NAME': None, 'PREFERRED_URL_SCHEME': 'http', 'JSONIFY_PRETTYPRINT_REGULAR': True, 'TESTING': False, 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(31), 'PROPAGATE_EXCEPTIONS': None, 'TRAP_BAD_REQUEST_ERRORS': False, 'JSON_SORT_KEYS': True, 'SESSION_COOKIE_HTTPONLY': True, 'SEND_FILE_MAX_AGE_DEFAULT': 43200, 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'SESSION_COOKIE_SECURE': False, 'TRAP_HTTP_EXCEPTIONS': 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()
.Changed in version 0.7: This no longer does the exception handling, this code was moved to the new
full_dispatch_request()
.
-
do_teardown_appcontext
(exc=None)¶ Called when an application context is popped. This works pretty much the same as
do_teardown_request()
but for the application context.New in version 0.9.
-
do_teardown_request
(exc=None)¶ Called after the actual request dispatching and will call every as
teardown_request()
decorated function. This is not actually called by theFlask
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.Changed in version 0.9: Added the exc argument. Previously this was always using the current exception information.
-
enable_modules
= True¶ Enable the deprecated module support? This is active by default in 0.7 but will be changed to False in 0.8. With Flask 1.0 modules will be removed in favor of Blueprints
-
endpoint
(*args, **kwargs)¶ A decorator to register a function as an endpoint. Example:
@app.endpoint('example.endpoint') def example(): return "example"
Parameters: 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 they 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
(*args, **kwargs)¶ 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 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.
New in version 0.7: One can now additionally also register custom exception types that do not necessarily have to be a subclass of the
HTTPException
class.Parameters: code – the code as integer for the handler
-
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 flaskext module. For example in case of a “Flask-Foo” extension in flaskext.foo, the key would be
'foo'
.New in version 0.7.
-
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.
New in version 0.7.
-
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 ofcurrent_app
.Static file functions such as
send_from_directory()
use this function, andsend_file()
calls this function oncurrent_app
when the given cache_timeout is None. If a cache_timeout is given insend_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)
New in version 0.9.
-
got_first_request
¶ This attribute is set to True if the application started handling the first request.
New in version 0.8.
-
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.
New in version 0.3.
-
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.
New in version 0.3.
-
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 thehandle_http_exception()
method. This function will either return a response value or reraise the exception with the same traceback.New in version 0.7.
-
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
()¶ Deprecated. Used to initialize the Jinja2 globals.
New in version 0.5.
Changed in version 0.7: This method is deprecated with 0.7. Override
create_jinja_environment()
instead.
-
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.
New in version 0.7.
-
instance_path
= None¶ Holds the path to the instance folder.
New in version 0.8.
-
jinja_env
¶ The Jinja2 environment used to load templates.
-
jinja_loader
¶ The Jinja loader for this package bound object.
New in version 0.5.
-
jinja_options
= ImmutableDict({'extensions': ['jinja2.ext.autoescape', 'jinja2.ext.with_']})¶ Options that are passed directly to the Jinja2 environment.
-
json_decoder
¶ The JSON decoder class to use. Defaults to
JSONDecoder
.New in version 0.10.
alias of
JSONDecoder
-
json_encoder
¶ The JSON encoder class to use. Defaults to
JSONEncoder
.New in version 0.10.
alias of
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 thelogger
.New in version 0.8.
-
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')
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_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.
New in version 0.8.
-
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.
New in version 0.7.
-
make_null_session
()¶ Creates a new instance of a missing session. Instead of overriding this method we recommend replacing the
session_interface
.New in version 0.7.
-
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 a WSGI function the function is called as WSGI application and buffered as response object tuple
A tuple in the form (response, status, headers)
where response is any of the types defined here, status is a string or an integer and headers is a list of a dictionary with header values.Parameters: rv – the return value from the view function Changed in version 0.9: Previously a tuple was interpreted as the arguments for the response object.
-
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.
New in version 0.8.
-
open_instance_resource
(resource, mode='rb')¶ Opens a resource from the application’s instance folder (
instance_path
). Otherwise works likeopen_resource()
. Instance resources can also be opened for writing.Parameters: - 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)
Parameters: - 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 thesession_interface
.Parameters: 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 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.This also triggers the
url_value_processor()
functions before the actualbefore_request()
functions are called.
-
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.
New in version 0.7.
-
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.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
.
-
propagate_exceptions
¶ Returns the value of the PROPAGATE_EXCEPTIONS configuration value in case it’s set, otherwise a sensible default is returned.
New in version 0.7.
-
register_blueprint
(*args, **kwargs)¶ Registers a blueprint on the application.
New in version 0.7.
-
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.New in version 0.7.
-
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.Changed in version 0.7: The module system was deprecated in favor for the blueprint system.
-
request_class
¶ The class that is used for request objects. See
Request
for more information.alias of
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()
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.alias of
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.
Parameters: - rule – the URL rule as string
- endpoint – the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint
- options – the options to be forwarded to the underlying
Rule
object. 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 for GET (and implicitly HEAD). 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. 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()
withdebug=True
anduse_reloader=False
. Settinguse_debugger
to True without being in debug mode won’t catch any exceptions because there won’t be any to catch.Changed in version 0.10: The default port is now picked from the
SERVER_NAME
variable.Parameters: - host – the hostname to listen on. Set this to
'<IP_ADDRESS>'
to have the server available externally as well. Defaults to'<IP_ADDRESS>'
. - 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.
- host – the hostname to listen on. Set this to
-
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 thesession_interface
.Parameters: - session – the session to be saved (a
SecureCookie
object) - response – an instance of
response_class
- session – the session to be saved (a
-
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'
-
session_interface
= <flask.sessions.SecureCookieSessionInterface object>¶ the session interface to use. By default an instance of
SecureCookieSessionInterface
is used here.New in version 0.8.
-
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.
New in version 0.10.
-
teardown_appcontext
(*args, **kwargs)¶ 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.
New in version 0.9.
-
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.
New in version 0.9.
-
teardown_request
(*args, **kwargs)¶ 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.
Debug Note
In debug mode Flask will not tear down a request on an exception immediately. Instead if 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.New in version 0.7.
-
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
(*args, **kwargs)¶ 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.
-
template_global
(*args, **kwargs)¶ 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
New in version 0.10.
Parameters: name – the optional name of the global function, otherwise the function name will be used.
-
template_test
(*args, **kwargs)¶ 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
New in version 0.10.
Parameters: name – the optional name of the test, otherwise the function name will be used.
-
test_client
(use_cookies=True)¶ 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 thetesting
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'
See
FlaskClient
for more information.Changed in version 0.4: added support for with block usage for the client.
New in version 0.7: The use_cookies parameter was added as well as the ability to override the client to be used by setting the
test_client_class
attribute.
-
test_client_class
= None¶ the test client that is used with when test_client is used.
New in version 0.7.
-
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 ifTRAP_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.
New in version 0.8.
-
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.
Parameters: context – 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 aBuildError
. 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.New in version 0.9.
-
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.New in version 0.7.
-
url_defaults
(*args, **kwargs)¶ 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(BaseConverter.to_url(value) for value in values) app = Flask(__name__) app.url_map.converters['list'] = ListConverter
-
url_rule_class
¶ The rule object to use for URL rules created. This is used by
add_url_rule()
. Defaults towerkzeug.routing.Rule
.New in version 0.7.
alias of
Rule
-
url_value_preprocessor
(*args, **kwargs)¶ 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
New in version 0.7.
-
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
= 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.
Changed in version 0.7: The behavior of the before and after request callbacks was changed under error conditions and a new callback was added that will always execute at the end of the request, independent on if an error occurred or not. See Callbacks and Errors.
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
Blueprint Objects¶
-
class
flask.
Blueprint
(name, import_name, static_folder=None, static_url_path=None, template_folder=None, url_prefix=None, subdomain=None, url_defaults=None)¶ Represents a blueprint. A blueprint is an object that records functions that will be called with the
BlueprintSetupState
later to register functions or other things on the main application. See Modular Applications with Blueprints for more information.New in version 0.7.
-
add_app_template_filter
(f, name=None)¶ Register a custom template filter, available application wide. Like
Flask.add_template_filter()
but for a blueprint. Works exactly like theapp_template_filter()
decorator.Parameters: name – the optional name of the filter, otherwise the function name will be used.
-
add_app_template_global
(f, name=None)¶ Register a custom template global, available application wide. Like
Flask.add_template_global()
but for a blueprint. Works exactly like theapp_template_global()
decorator.New in version 0.10.
Parameters: name – the optional name of the global, otherwise the function name will be used.
-
add_app_template_test
(f, name=None)¶ Register a custom template test, available application wide. Like
Flask.add_template_test()
but for a blueprint. Works exactly like theapp_template_test()
decorator.New in version 0.10.
Parameters: name – the optional name of the test, otherwise the function name will be used.
-
add_url_rule
(rule, endpoint=None, view_func=None, **options)¶ Like
Flask.add_url_rule()
but for a blueprint. The endpoint for theurl_for()
function is prefixed with the name of the blueprint.
-
after_app_request
(f)¶ Like
Flask.after_request()
but for a blueprint. Such a function is executed after each request, even if outside of the blueprint.
-
after_request
(f)¶ Like
Flask.after_request()
but for a blueprint. This function is only executed after each request that is handled by a function of that blueprint.
-
app_context_processor
(f)¶ Like
Flask.context_processor()
but for a blueprint. Such a function is executed each request, even if outside of the blueprint.
-
app_errorhandler
(code)¶ Like
Flask.errorhandler()
but for a blueprint. This handler is used for all requests, even if outside of the blueprint.
-
app_template_filter
(name=None)¶ Register a custom template filter, available application wide. Like
Flask.template_filter()
but for a blueprint.Parameters: name – the optional name of the filter, otherwise the function name will be used.
-
app_template_global
(name=None)¶ Register a custom template global, available application wide. Like
Flask.template_global()
but for a blueprint.New in version 0.10.
Parameters: name – the optional name of the global, otherwise the function name will be used.
-
app_template_test
(name=None)¶ Register a custom template test, available application wide. Like
Flask.template_test()
but for a blueprint.New in version 0.10.
Parameters: name – the optional name of the test, otherwise the function name will be used.
-
app_url_defaults
(f)¶ Same as
url_defaults()
but application wide.
-
app_url_value_preprocessor
(f)¶ Same as
url_value_preprocessor()
but application wide.
-
before_app_first_request
(f)¶ Like
Flask.before_first_request()
. Such a function is executed before the first request to the application.
-
before_app_request
(f)¶ Like
Flask.before_request()
. Such a function is executed before each request, even if outside of a blueprint.
-
before_request
(f)¶ Like
Flask.before_request()
but for a blueprint. This function is only executed before each request that is handled by a function of that blueprint.
-
context_processor
(f)¶ Like
Flask.context_processor()
but for a blueprint. This function is only executed for requests handled by a blueprint.
-
endpoint
(endpoint)¶ Like
Flask.endpoint()
but for a blueprint. This does not prefix the endpoint with the blueprint name, this has to be done explicitly by the user of this method. If the endpoint is prefixed with a . it will be registered to the current blueprint, otherwise it’s an application independent endpoint.
-
errorhandler
(code_or_exception)¶ Registers an error handler that becomes active for this blueprint only. Please be aware that routing does not happen local to a blueprint so an error handler for 404 usually is not handled by a blueprint unless it is caused inside a view function. Another special case is the 500 internal server error which is always looked up from the application.
Otherwise works as the
errorhandler()
decorator of theFlask
object.
-
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 ofcurrent_app
.Static file functions such as
send_from_directory()
use this function, andsend_file()
calls this function oncurrent_app
when the given cache_timeout is None. If a cache_timeout is given insend_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)
New in version 0.9.
-
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.
-
make_setup_state
(app, options, first_registration=False)¶ Creates an instance of
BlueprintSetupState()
object that is later passed to the register callback functions. Subclasses can override this to return a subclass of the setup state.
-
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)
Parameters: - resource – the name of the resource. To access resources within subfolders use forward slashes as separator.
- mode – resource file opening mode, default is ‘rb’.
-
record
(func)¶ Registers a function that is called when the blueprint is registered on the application. This function is called with the state as argument as returned by the
make_setup_state()
method.
-
record_once
(func)¶ Works like
record()
but wraps the function in another function that will ensure the function is only called once. If the blueprint is registered a second time on the application, the function passed is not called.
-
register
(app, options, first_registration=False)¶ Called by
Flask.register_blueprint()
to register a blueprint on the application. This can be overridden to customize the register behavior. Keyword arguments fromregister_blueprint()
are directly forwarded to this method in the options dictionary.
-
route
(rule, **options)¶ Like
Flask.route()
but for a blueprint. The endpoint for theurl_for()
function is prefixed with the name of the blueprint.
-
send_static_file
(filename)¶ Function used internally to send static files from the static folder to the browser.
New in version 0.5.
-
teardown_app_request
(f)¶ Like
Flask.teardown_request()
but for a blueprint. Such a function is executed when tearing down each request, even if outside of the blueprint.
-
teardown_request
(f)¶ Like
Flask.teardown_request()
but for a blueprint. This function is only executed when tearing down requests handled by a function of that blueprint. Teardown request functions are executed when the request context is popped, even when no actual request was performed.
-
url_defaults
(f)¶ Callback function for URL defaults for this blueprint. It’s called with the endpoint and values and should update the values passed in place.
-
url_value_preprocessor
(f)¶ Registers a function as URL value preprocessor for this blueprint. It’s called before the view functions are called and can modify the url values provided.
-
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 setrequest_class
to your subclass.The request object is a
Request
subclass and provides all of the attributes Werkzeug defines plus a few Flask specific 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 thefiles
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 bothform
andargs
.
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.
-
headers
¶ The incoming request headers as a dictionary like object.
-
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 asFileStorage
object. It basically behaves like a standard file object you know from Python, with the difference that it also has asave()
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.
-
blueprint
¶ The name of the current blueprint
-
endpoint
¶ The endpoint that matched the request. This in combination with
view_args
can be used to reconstruct the same or a modified URL. If an exception happened when matching, this will be None.
-
get_json
(force=False, silent=False, cache=True)¶ Parses the incoming JSON request data and returns it. If parsing fails the
on_json_loading_failed()
method on the request object will be invoked. By default this function will only load the json data if the mimetype isapplication/json
but this can be overriden by the force parameter.Parameters: - force – if set to True the mimetype is ignored.
- silent – if set to False this method will fail silently and return False.
- cache – if set to True the parsed JSON data is remembered on the request.
-
json
¶ If the mimetype is application/json this will contain the parsed JSON data. Otherwise this will be None.
The
get_json()
method should be used instead.
-
max_content_length
¶ Read-only view of the MAX_CONTENT_LENGTH config key.
-
module
¶ The name of the current module if the request was dispatched to an actual module. This is deprecated functionality, use blueprints instead.
-
on_json_loading_failed
(e)¶ Called if decoding of the JSON data failed. The return value of this method is used by
get_json()
when an error occurred. The default implementation just raises aBadRequest
exception.Changed in version 0.10: Removed buggy previous behavior of generating a random JSON response. If you want that behavior back you can trivially add it by subclassing.
New in version 0.8.
-
routing_exception
= None¶ if matching the URL failed, this is the exception that will be raised / was raised as part of the request handling. This is usually a
NotFound
exception or something similar.
-
url_rule
= None¶ the internal URL rule that matched the request. This can be useful to inspect which methods are allowed for the URL from a before/after handler (
request.url_rule.methods
) etc.New in version 0.6.
-
view_args
= None¶ a dict of view arguments that matched the request. If an exception happened when matching, this will be None.
-
-
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.
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.
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 an 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
¶ A string with a response status.
-
status_code
¶ The response status as integer.
-
data
¶ A descriptor that calls
get_data()
andset_data()
. This should not be used and will eventually get deprecated.
-
mimetype
¶ The mimetype (content type without charset etc.)
Sets a cookie. The parameters are the same as in the cookie Morsel object in the Python standard library but it accepts unicode data, too.
Parameters: - key – the key (name) of the cookie to be set.
- value – the value of the cookie.
- max_age – should be a number of seconds, or None (default) if the cookie should last only as long as the client’s browser session.
- expires – should be a datetime object or UNIX timestamp.
- domain – if you want to set a cross-domain cookie. For example,
domain=".example.com"
will set a cookie that is readable by the domainwww.example.com
,foo.example.com
etc. Otherwise, a cookie will only be readable by the domain that set it. - path – limits the cookie to a given path, per default it will span the whole domain.
-
Sessions¶
If you have the Flask.secret_key
set you can use sessions in Flask
applications. A session basically makes it possible to remember
information from one request to another. The way Flask does this is by
using a signed cookie. So the user can look at the session contents, but
not modify it unless they know 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.
This is a proxy. See Notes On Proxies for more information.
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 lives 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.
-
Session Interface¶
New in version 0.8.
The session interface provides a simple way to replace the session implementation that Flask is using.
-
class
flask.sessions.
SessionInterface
¶ The basic interface you have to implement in order to replace the default session interface which uses werkzeug’s securecookie implementation. The only methods you have to implement are
open_session()
andsave_session()
, the others have useful defaults which you don’t need to change.The session object returned by the
open_session()
method has to provide a dictionary like interface plus the properties and methods from theSessionMixin
. We recommend just subclassing a dict and adding that mixin:class Session(dict, SessionMixin): pass
If
open_session()
returns None Flask will call intomake_null_session()
to create a session that acts as replacement if the session support cannot work because some requirement is not fulfilled. The defaultNullSession
class that is created will complain that the secret key was not set.To replace the session interface on an application all you have to do is to assign
flask.Flask.session_interface
:app = Flask(__name__) app.session_interface = MySessionInterface()
New in version 0.8.
Helpful helper method that returns the cookie domain that should be used for the session cookie if session cookies are used.
Returns True if the session cookie should be httponly. This currently just returns the value of the
SESSION_COOKIE_HTTPONLY
config var.
Returns the path for which the cookie should be valid. The default implementation uses the value from the SESSION_COOKIE_PATH`` config var if it’s set, and falls back to
APPLICATION_ROOT
or uses/
if it’s None.
Returns True if the cookie should be secure. This currently just returns the value of the
SESSION_COOKIE_SECURE
setting.
-
get_expiration_time
(app, session)¶ A helper method that returns an expiration date for the session or None if the session is linked to the browser session. The default implementation returns now + the permanent session lifetime configured on the application.
-
is_null_session
(obj)¶ Checks if a given object is a null session. Null sessions are not asked to be saved.
This checks if the object is an instance of
null_session_class
by default.
-
make_null_session
(app)¶ Creates a null session which acts as a replacement object if the real session support could not be loaded due to a configuration error. This mainly aids the user experience because the job of the null session is to still support lookup without complaining but modifications are answered with a helpful error message of what failed.
This creates an instance of
null_session_class
by default.
-
null_session_class
¶ make_null_session()
will look here for the class that should be created when a null session is requested. Likewise theis_null_session()
method will perform a typecheck against this type.alias of
NullSession
-
open_session
(app, request)¶ This method has to be implemented and must either return None in case the loading failed because of a configuration error or an instance of a session object which implements a dictionary like interface + the methods and attributes on
SessionMixin
.
-
pickle_based
= False¶ A flag that indicates if the session interface is pickle based. This can be used by flask extensions to make a decision in regards to how to deal with the session object.
New in version 0.10.
-
save_session
(app, session, response)¶ This is called for actual sessions returned by
open_session()
at the end of the request. This is still called during a request context so if you absolutely need access to the request you can do that.
-
class
flask.sessions.
SecureCookieSessionInterface
¶ The default session interface that stores sessions in signed cookies through the
itsdangerous
module.-
static
digest_method
()¶ the hash function to use for the signature. The default is sha1
-
key_derivation
= 'hmac'¶ the name of the itsdangerous supported key derivation. The default is hmac.
-
salt
= 'cookie-session'¶ the salt that should be applied on top of the secret key for the signing of cookie based sessions.
-
serializer
= <flask.sessions.TaggedJSONSerializer object>¶ A python serializer for the payload. The default is a compact JSON derived serializer with support for some extra Python types such as datetime objects or tuples.
-
session_class
¶ alias of
SecureCookieSession
-
static
-
class
flask.sessions.
SecureCookieSession
(initial=None)¶ Baseclass for sessions based on signed cookies.
-
class
flask.sessions.
NullSession
(initial=None)¶ Class used to generate nicer error messages if sessions are not available. Will still allow read-only access to the empty session but fail on setting.
-
class
flask.sessions.
SessionMixin
¶ Expands a basic dictionary with an accessors that are expected by Flask extensions and users for the session.
-
modified
= True¶ for some backends this will always be True, but some backends will default this to false and detect changes in the dictionary for as long as changes do not happen on mutable structures in the session. The default mixin implementation just hardcodes True in.
-
new
= False¶ some session backends can tell you if a session is new, but that is not necessarily guaranteed. Use with caution. The default mixin implementation just hardcodes False in.
-
permanent
¶ this reflects the
'_permanent'
key in the dict.
-
-
flask.sessions.
session_json_serializer
= <flask.sessions.TaggedJSONSerializer object>¶ A customized JSON serializer that supports a few extra types that we take for granted when serializing (tuples, markup objects, datetime).
This object provides dumping and loading methods similar to simplejson but it also tags certain builtin Python objects that commonly appear in sessions. Currently the following extended values are supported in the JSON it dumps:
Notice
The PERMANENT_SESSION_LIFETIME
config key can also be an integer
starting with Flask 0.8. Either catch this down yourself or use
the permanent_session_lifetime
attribute on the
app which converts the result to an integer automatically.
Test Client¶
-
class
flask.testing.
FlaskClient
(application, response_wrapper=None, use_cookies=True, allow_subdomain_redirects=False)¶ Works like a regular Werkzeug test client but has some knowledge about how Flask works to defer the cleanup of the request context stack to the end of a with body when used in a with statement. For general information about how to use this class refer to
werkzeug.test.Client
.Basic usage is outlined in the Testing Flask Applications chapter.
-
session_transaction
(*args, **kwds)¶ When used in combination with a with statement this opens a session transaction. This can be used to modify the session that the test client uses. Once the with block is left the session is stored back.
- with client.session_transaction() as session:
- session[‘value’] = 42
Internally this is implemented by going through a temporary test request context and since session handling could depend on request variables this function accepts the same arguments as
test_request_context()
which are directly passed through.
-
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


Describing a node¶
Centrality Measurements¶
Note
First of all, how should we define centrality? It just indicates the node is “central” to the network, which could indicate some sort of importance, significance, or having an advantaged position. However, that there are lots of specific ways we can think of centrality, and thus different ways of mathematically defining the concept.
Degree Centrality¶
Degree centrality measures how connected is a node. Thus, the degree of a node is a simple measure of centrality in which more highly connected nodes rank higher.
import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
G = nx.generators.social.florentine_families_graph()
print("Node Degree")
for v in G:
print(f"{v:4} {G.degree(v):6}")
fig, ax = plt.subplots(1, 1, figsize=(8, 6))
nx.draw_networkx(G, with_labels=True,ax=ax)
plt.show()
Node Degree
Acciaiuoli 1
Medici 6
Castellani 3
Peruzzi 3
Strozzi 4
Barbadori 2
Ridolfi 3
Tornabuoni 3
Albizzi 3
Salviati 2
Pazzi 1
Bischeri 3
Guadagni 4
Ginori 1
Lamberteschi 1
We can also normalize the degree centrality by dividing by the maximum possible degree in a simple graph \(n-1\) where \(n\) is the number of nodes in \(G\).
sorted(nx.centrality.degree_centrality(G).items(), key=lambda item: item[1])
[('Acciaiuoli', 0.07142857142857142),
('Pazzi', 0.07142857142857142),
('Ginori', 0.07142857142857142),
('Lamberteschi', 0.07142857142857142),
('Barbadori', 0.14285714285714285),
('Salviati', 0.14285714285714285),
('Castellani', 0.21428571428571427),
('Peruzzi', 0.21428571428571427),
('Ridolfi', 0.21428571428571427),
('Tornabuoni', 0.21428571428571427),
('Albizzi', 0.21428571428571427),
('Bischeri', 0.21428571428571427),
('Strozzi', 0.2857142857142857),
('Guadagni', 0.2857142857142857),
('Medici', 0.42857142857142855)]
In-degree & Out-degree Centrality¶
The in-degree centrality for a node v is the fraction of nodes its incoming edges are connected to. The out-degree centrality for a node v is the fraction of nodes its outgoing edges are connected to.
G_di=nx.fast_gnp_random_graph(10, 0.2, directed=True, seed=2021)
nx.draw_circular(G_di, with_labels=True)
print(G_di.degree)
print(G_di.out_degree)
print(G_di.in_degree)
[(0, 1), (1, 3), (2, 4), (3, 2), (4, 5), (5, 5), (6, 2), (7, 3), (8, 5), (9, 4)]
[(0, 1), (1, 1), (2, 3), (3, 0), (4, 3), (5, 2), (6, 2), (7, 1), (8, 2), (9, 2)]
[(0, 0), (1, 2), (2, 1), (3, 2), (4, 2), (5, 3), (6, 0), (7, 2), (8, 3), (9, 2)]
nx.degree_centrality(G_di)
{0: 0.1111111111111111,
1: 0.3333333333333333,
2: 0.4444444444444444,
3: 0.2222222222222222,
4: 0.5555555555555556,
5: 0.5555555555555556,
6: 0.2222222222222222,
7: 0.3333333333333333,
8: 0.5555555555555556,
9: 0.4444444444444444}
nx.out_degree_centrality(G_di)
{0: 0.1111111111111111,
1: 0.1111111111111111,
2: 0.3333333333333333,
3: 0.0,
4: 0.3333333333333333,
5: 0.2222222222222222,
6: 0.2222222222222222,
7: 0.1111111111111111,
8: 0.2222222222222222,
9: 0.2222222222222222}
Closeness Centrality¶
Closeness centraloity is a measurement of the ease of reaching of other nodes. How far am I on average from other nodes? It is defined as \(n-1 \over \sum_{j} L(i,j) \). L is the length of the shortest distance between node \(i\) and \(j\).
Or in simple words closeness is (number of nodes - 1) / sum(distance from node to all other nodes)
sorted(nx.centrality.closeness_centrality(G).items(), key=lambda item: item[1])
[('Pazzi', 0.2857142857142857),
('Lamberteschi', 0.32558139534883723),
('Ginori', 0.3333333333333333),
('Acciaiuoli', 0.3684210526315789),
('Peruzzi', 0.3684210526315789),
('Castellani', 0.3888888888888889),
('Salviati', 0.3888888888888889),
('Bischeri', 0.4),
('Strozzi', 0.4375),
('Barbadori', 0.4375),
('Guadagni', 0.4666666666666667),
('Tornabuoni', 0.4827586206896552),
('Albizzi', 0.4827586206896552),
('Ridolfi', 0.5),
('Medici', 0.56)]
Decay Centrality¶
Decay Centrality is very similar to closeness centrality as they all weighs the distance of the node to the rest of the nodes. Unlike closeness centraity, it is based of a decay parameter (0 < δ < 1). \(\sum_{j\neq i} δ^{L(i,j)} \).
You have to decide the δ and the basic idea is my direct friend (l=1) get the value of \(δ^1\) while my friend’s friend got value of \(δ^2\), to \(δ^n\). Then you add them up and got this value.
Higher the δ, the more focus was put on close connections. It weights distance exponentially.
Normalized version: \(\sum_{j\neq i} δ^{L(i,j)} \over (n-1)δ\)
\((n-1)δ\) is the lowest decay possible (where every node is directed connected)
Betweenness Centrality¶
The idea is idea here is that when we look at two nodes, i and j, we can keep track of the full number of shortest paths between i and j. And then for any k that’s not equal to i and j, we can ask what’s the number of those shortest paths that k lies on, between i and j. A formal definition would be:
\(\sum_{i,j \neq k} {p_k(i, j) \over p(i, j)} \)
In a mroe simple words, Betweennewhat’s the fraction of shortest paths that k lies on between other nodes.
We can normalize the value by dividing it by \(2 \over (n-1)(n-2)\)
sorted(nx.centrality.betweenness_centrality(G).items(), key=lambda item: item[1])
[('Acciaiuoli', 0.0),
('Pazzi', 0.0),
('Ginori', 0.0),
('Lamberteschi', 0.0),
('Peruzzi', 0.02197802197802198),
('Castellani', 0.05494505494505495),
('Tornabuoni', 0.09157509157509157),
('Barbadori', 0.09340659340659341),
('Strozzi', 0.10256410256410257),
('Bischeri', 0.1043956043956044),
('Ridolfi', 0.11355311355311355),
('Salviati', 0.14285714285714288),
('Albizzi', 0.21245421245421245),
('Guadagni', 0.2545787545787546),
('Medici', 0.521978021978022)]
Eigenvector Centrality¶
Eigenvector centrality mesaures not only how many people you connect with, but also how many people are conneected with the people you are connected with. S the idea of eigenvector centrality is that your importance comes from being connected to other important.
\(C_i\) is porportional to \(\sum_{j:friends of i} C_j\)
It actually shares similar idea of a Markov process. Those egenvalues are from the eigenvector of the transition matrix when reaching stationary distribution.
sorted(nx.centrality.eigenvector_centrality(G).items(), key=lambda item: item[1])
[('Pazzi', 0.044814939703863084),
('Ginori', 0.0749245316027793),
('Lamberteschi', 0.08879253113499548),
('Acciaiuoli', 0.1321573195285342),
('Salviati', 0.14592084164171834),
('Barbadori', 0.2117057470647985),
('Albizzi', 0.2439605296754477),
('Castellani', 0.2590200378423514),
('Peruzzi', 0.2757224374104833),
('Bischeri', 0.2827943958713356),
('Guadagni', 0.2891171573226501),
('Tornabuoni', 0.325846704169574),
('Ridolfi', 0.3415544259074365),
('Strozzi', 0.3559730326460451),
('Medici', 0.4303154258349923)]
Kat’z Centrality¶
Similar to eigenvector centrality, it used the weighted counts of all paths coming tot he node. The weight of path of lenght n is counted with attenuation factor. \(k_i = β \sum_{j}A_{ij} + β^2 \sum_{j}A^2_{ij}+ ... \)
sorted(nx.centrality.katz_centrality(G).items(), key=lambda item: item[1])
[('Pazzi', 0.20681510895407593),
('Ginori', 0.20969166397130154),
('Lamberteschi', 0.21157675618005328),
('Acciaiuoli', 0.2164813014337632),
('Salviati', 0.2371628109637314),
('Barbadori', 0.2427683603055736),
('Castellani', 0.26287066557722627),
('Peruzzi', 0.26508006405086565),
('Albizzi', 0.26592838962649556),
('Bischeri', 0.26707175982033843),
('Tornabuoni', 0.2722283284383517),
('Ridolfi', 0.27269113011871177),
('Guadagni', 0.28477932796167227),
('Strozzi', 0.28987015981269015),
('Medici', 0.3338248231609825)]
Summary¶
Degree: connectness
Closeness: ease of reaching out nodes
Betweenness: role of being a connector, intermediary
Eigenvector: connecting to important people


--- layout:post categories:toeza tags:toeza title:How to Play Jacks and Fives date:2016-12-07 14:32:45 +0800 --- Edit Article
Community Q&A
Jacks and Fives is a fun and easy card game you can play anywhere. So grab a friend and a deck of cards and learn to play this game!


The Sharpe ratio is likely the most common performance measurement as it conveys much information very quickly. Despite its limitations, a number expressing risk-adjusted performance is a valuable tool that investors use to screen algorithms. Sharpe ratios need to be positive, but a good minimum to aim for is an annualized Sharpe ratio of 1.
Drawdown is the total decline from a strategy's maximum value to its lowest value over a specified period. It is a good measure of risk and performance and is something that is closely scrutinized by investors. Algorithms with consistent returns and low drawdown are more likely to provide value to investors than a strategy with higher overall returns and a significant drawdown, which demonstrates higher strategy risk and volatility.
Time underwater is the amount of time that a strategy is in a drawdown. That is, the amount of time a strategy spends below its peak value before recovering. A short time underwater demonstrates resilience and adaptability, reassuring investors that any time spent underwater is likely to be short-lived and that losses will be recovered.
Due to borrowing costs, funds often want to be dollar-neutral in their strategies. A strategy that achieves this helps offset the cost of trading on margin and reduces exposure risk. Not all strategies need to be market-neutral, but it is a feature that is common among high-value Alphas.