flask package¶
Subpackages¶
Submodules¶
flask.app module¶
flask.app¶
This module implements the central WSGI application object.
| copyright: |
|
|---|---|
| license: | BSD, see LICENSE for more details. |
-
class
flask.app.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)[source]¶ Bases:
flask.helpers._PackageBoundObjectThe 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__.pyfile inside) or a standard module (just a.pyfile).For more information about resource loading, see
open_resource().Usually you create a
Flaskinstance in your main module or in the__init__.pyfile 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.pyyou 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.
New in version 0.11: The root_path parameter was 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
Truerelative 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)[source]¶ 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(f, name=None)[source]¶ 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(f, name=None)[source]¶ 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(rule, endpoint=None, view_func=None, **options)[source]¶ 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:
OPTIONSis 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
Ruleobject. A change to Werkzeug is handling of method options. methods is a list of methods this rule should be limited to (GET,POSTetc.). By default a rule just listens forGET(and implicitlyHEAD). Starting with Flask 0.6,OPTIONSis implicitly added and handled by the standard request handling.
-
after_request(f)[source]¶ Register a function to be run after each request.
Your function must take one parameter, an instance of
response_classand 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,
Nonefor all requests. This can for example be used to close database connections. To register a function here, use theafter_request()decorator.
-
app_context()[source]¶ Binds the application only. For as long as the application is bound to the current context the
flask.current_apppoints 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
ginstance.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 unexpected 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_classbecause the flask.g object is now application context scoped.New in version 0.10.
alias of
_AppCtxGlobals
-
auto_find_instance_path()[source]¶ 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
instancenext to your main file or the package.New in version 0.8.
-
before_first_request(f)[source]¶ 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.
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(f)[source]¶ 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,
Nonefor 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 thebefore_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.
-
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.Groupobject.
-
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¶ The class that is used for the
configattribute of this app. Defaults toConfig.Example use cases for a custom class:
- Default values for certain config options.
- Access to config values through attributes in addition to keys.
New in version 0.11.
alias of
Config
-
create_global_jinja_loader()[source]¶ 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()[source]¶ Creates the Jinja2 environment based on
jinja_optionsandselect_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.
Changed in version 0.11:
Environment.auto_reloadset in accordance withTEMPLATES_AUTO_RELOADconfiguration option.
-
create_url_adapter(request)[source]¶ 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
Trueto 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
DEBUGconfiguration key. Defaults toFalse.
-
default_config= ImmutableDict({'JSON_AS_ASCII': True, 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(31), 'SESSION_COOKIE_SECURE': False, 'LOGGER_HANDLER_POLICY': 'always', 'SESSION_COOKIE_DOMAIN': None, 'SESSION_COOKIE_NAME': 'session', 'SESSION_REFRESH_EACH_REQUEST': True, 'TRAP_BAD_REQUEST_ERRORS': False, 'PREFERRED_URL_SCHEME': 'http', 'APPLICATION_ROOT': None, 'LOGGER_NAME': None, 'TEMPLATES_AUTO_RELOAD': None, 'EXPLAIN_TEMPLATE_LOADING': False, 'PROPAGATE_EXCEPTIONS': None, 'SESSION_COOKIE_HTTPONLY': True, 'JSON_SORT_KEYS': True, 'TESTING': False, 'TRAP_HTTP_EXCEPTIONS': False, 'SERVER_NAME': None, 'SECRET_KEY': None, 'USE_X_SENDFILE': False, 'DEBUG': False, 'MAX_CONTENT_LENGTH': None, 'SESSION_COOKIE_PATH': None, 'SEND_FILE_MAX_AGE_DEFAULT': datetime.timedelta(0, 43200), 'JSONIFY_MIMETYPE': 'application/json', 'JSONIFY_PRETTYPRINT_REGULAR': True})¶ Default configuration parameters.
-
dispatch_request()[source]¶ 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=<object object at 0x000001E1FDEFF7A0>)[source]¶ 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=<object object at 0x000001E1FDEFF7A0>)[source]¶ Called after the actual request dispatching and will call every as
teardown_request()decorated function. This is not actually called by theFlaskobject 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.
-
endpoint(endpoint)[source]¶ 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
Nonefor 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 keyNonepoints 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.
-
error_handlers¶
-
errorhandler(code_or_exception)[source]¶ 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_spechowever is discouraged as it requires fiddling with nested dictionaries and the special case for arbitrary exception types.The first
Nonerefers to the active blueprint. If the error handler should be application wideNoneshall be used.New in version 0.7: Use
register_error_handler()instead of modifyingerror_handler_specdirectly, for application wide error handlers.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
HTTPExceptionclass.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 extension module. For example in case of a “Flask-Foo” extension in flask_foo, the key would be
'foo'.New in version 0.7.
-
full_dispatch_request()[source]¶ 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.
-
got_first_request¶ This attribute is set to
Trueif the application started handling the first request.New in version 0.8.
-
handle_exception(e)[source]¶ 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)[source]¶ 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)[source]¶ This method is called whenever an exception occurs that should be handled. A special case are
HTTPExceptions 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.
-
init_jinja_globals()[source]¶ 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)[source]¶ 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.
-
iter_blueprints()[source]¶ Iterates over all blueprints by the order they were registered.
New in version 0.11.
-
jinja_environment¶ The class that is used for the Jinja environment.
New in version 0.11.
alias of
Environment
-
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)[source]¶ 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.Loggerobject 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)[source]¶ 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()[source]¶ This method is called to create the default
OPTIONSresponse. This can be changed through subclassing to change the default behavior ofOPTIONSresponses.New in version 0.7.
-
make_null_session()[source]¶ 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)[source]¶ 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_classthe object is returned unchanged stra response object is created with the string as body unicodea 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 tupleA 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.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.
-
make_shell_context()[source]¶ Returns the shell context for an interactive shell for this application. This runs all the registered shell context processors.
New in version 0.11.
-
name[source]¶ 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')[source]¶ 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_session(request)[source]¶ Creates or opens a new session. Default implementation stores all session data in a signed cookie. This requires that the
secret_keyis set. Instead of overriding this method we recommend replacing thesession_interface.Parameters: request – an instance of request_class.
-
permanent_session_lifetime¶ A
timedeltawhich 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_LIFETIMEconfiguration key. Defaults totimedelta(days=31)
-
preprocess_request()[source]¶ 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_processor()functions before the actualbefore_request()functions are called.
-
preserve_context_on_exception¶ Returns the value of the
PRESERVE_CONTEXT_ON_EXCEPTIONconfiguration value in case it’s set, otherwise a sensible default is returned.New in version 0.7.
-
process_response(response)[source]¶ 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_classobject.Returns: a new response object or the same, has to be an instance of response_class.
-
propagate_exceptions¶ Returns the value of the
PROPAGATE_EXCEPTIONSconfiguration value in case it’s set, otherwise a sensible default is returned.New in version 0.7.
-
raise_routing_exception(request)[source]¶ Exceptions that are recording during routing are reraised with this method. During debug we are not reraising redirect requests for non
GET,HEAD, orOPTIONSrequests and we’re raising a different error instead to help debug situations.Internal:
-
register_blueprint(blueprint, **options)[source]¶ Register a blueprint on the application. For information about blueprints head over to blueprints.
The blueprint name is passed in as the first argument. Options are passed as additional keyword arguments and forwarded to blueprints in an “options” dictionary.
Parameters: - subdomain – set a subdomain for the blueprint
- url_prefix – set the prefix for all URLs defined on the blueprint.
(url_prefix='/<lang code>') - url_defaults – a dictionary with URL defaults that is added to each and every URL defined with this blueprint
- static_folder – add a static folder to urls in this blueprint
- static_url_path – add a static url path to urls in this blueprint
- template_folder – set an alternate template folder
- root_path – set an alternate root path for this blueprint
New in version 0.7.
-
register_error_handler(code_or_exception, f)[source]¶ Alternative error attach function to the
errorhandler()decorator that is more straightforward to use for non decorator usage.New in version 0.7.
-
request_class¶ The class that is used for request objects. See
Requestfor more information.alias of
Request
-
request_context(environ)[source]¶ Creates a
RequestContextfrom the given environment and binds it to the current context. This must be used in combination with thewithstatement because the request is only bound to the current context for the duration of thewithblock.Example usage:
with app.request_context(environ): do_something_with(request)
The object returned can also be used without the
withstatement 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
withstatement is now passed the ctx object.Parameters: environ – a WSGI environment
-
request_globals_class¶
-
response_class¶ The class that is used for response objects. See
Responsefor more information.alias of
Response
-
route(rule, **options)[source]¶ 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
Ruleobject. A change to Werkzeug is handling of method options. methods is a list of methods this rule should be limited to (GET,POSTetc.). By default a rule just listens forGET(and implicitlyHEAD). Starting with Flask 0.6,OPTIONSis implicitly added and handled by the standard request handling.
-
run(host=None, port=None, debug=None, **options)[source]¶ 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 for WSGI server recommendations.If the
debugflag 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=Falseas 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
runsupport.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=Trueanduse_reloader=False. Settinguse_debuggertoTruewithout 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_NAMEvariable.Parameters: - 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
5000or the port defined in theSERVER_NAMEconfig 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)[source]¶ 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
SecureCookieobject) - 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_KEYconfiguration key. Defaults toNone.
-
select_jinja_autoescape(filename)[source]¶ Returns
Trueif autoescaping should be active for the given template name. If no template name is given, returns True.New in version 0.5.
-
send_file_max_age_default¶ A
timedeltawhich is used as default cache_timeout for thesend_file()functions. The default is 12 hours.This attribute can also be configured from the config with the
SEND_FILE_MAX_AGE_DEFAULTconfiguration key. This configuration variable can also be set with an integer value used as seconds. Defaults totimedelta(hours=12)
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_NAMEconfiguration key. Defaults to'session'
-
session_interface= <flask.sessions.SecureCookieSessionInterface object at 0x000001E1821AB278>¶ the session interface to use. By default an instance of
SecureCookieSessionInterfaceis used here.New in version 0.8.
-
shell_context_processor(f)[source]¶ Registers a shell context processor function.
New in version 0.11.
-
shell_context_processors= None¶ A list of shell context processor functions that should be run when a shell context is created.
New in version 0.11.
-
should_ignore_error(error)[source]¶ 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
Truethen the teardown handlers will not be passed the error.New in version 0.10.
-
teardown_appcontext(f)[source]¶ 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.
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(f)[source]¶ 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_EXCEPTIONconfiguration 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,
Nonefor 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 theteardown_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,
Nonefor all requests. Each returns a dictionary that the template context is updated with. To register a function here, use thecontext_processor()decorator.
-
template_filter(name=None)[source]¶ 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(name=None)[source]¶ 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(name=None)[source]¶ 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, **kwargs)[source]¶ Creates a test client for this application. For information about unit testing head over to testing.
Note that if you are testing for assertions or exceptions in your application code, you must set
app.testing = Truein 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 thetestingattribute. For example:app.testing = True client = app.test_client()
The test client can be used in a
withblock to defer the closing down of the context until the end of thewithblock. 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_classconstructor. For example:from flask.testing import FlaskClient class CustomClient(FlaskClient): def __init__(self, authentication=None, *args, **kwargs): FlaskClient.__init__(*args, **kwargs) self._authentication = authentication app.test_client_class = CustomClient client = app.test_client(authentication='Basic ....')
See
FlaskClientfor more information.Changed in version 0.4: added support for
withblock 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_classattribute.Changed in version 0.11: Added **kwargs to support passing additional keyword arguments to the constructor of
test_client_class.
-
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)[source]¶ Creates a WSGI environment from the given values (see
werkzeug.test.EnvironBuilderfor more information, this function accepts the same arguments).
-
testing¶ The testing flag. Set this to
Trueto 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
TESTINGconfiguration key. Defaults toFalse.
-
trap_http_exception(e)[source]¶ Checks if an HTTP exception should be trapped or not. By default this will return
Falsefor all exceptions except for a bad request key error ifTRAP_BAD_REQUEST_ERRORSis set toTrue. It also returnsTrueifTRAP_HTTP_EXCEPTIONSis set toTrue.This is called for all HTTP exceptions raised by a view function. If it returns
Truefor 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.
-
try_trigger_before_first_request_functions()[source]¶ Called before each request and will ensure that it triggers the
before_first_request_funcsand only exactly once per application instance (which means process usually).Internal:
-
update_template_context(context)[source]¶ 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 returnsNoneor raises aBuildErrorthe 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
Nonehere 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 aurl_defaults()function that adds the parameters automatically again that were removed that way.New in version 0.7.
-
url_defaults(f)[source]¶ 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
Mapfor 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(f)[source]¶ 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
Nonehere 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 dictionaryNew 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_SENDFILEconfiguration key. Defaults toFalse.
-
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)[source]¶ 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
flask.blueprints module¶
flask.blueprints¶
Blueprints are the recommended way to implement larger or more pluggable applications in Flask 0.7 and later.
| copyright: |
|
|---|---|
| license: | BSD, see LICENSE for more details. |
-
class
flask.blueprints.Blueprint(name, import_name, static_folder=None, static_url_path=None, template_folder=None, url_prefix=None, subdomain=None, url_defaults=None, root_path=None)[source]¶ Bases:
flask.helpers._PackageBoundObjectRepresents a blueprint. A blueprint is an object that records functions that will be called with the
BlueprintSetupStatelater to register functions or other things on the main application. See blueprints for more information.New in version 0.7.
-
add_app_template_filter(f, name=None)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ Like
Flask.context_processor()but for a blueprint. Such a function is executed each request, even if outside of the blueprint.
-
app_errorhandler(code)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ Same as
url_defaults()but application wide.
-
app_url_value_preprocessor(f)[source]¶ Same as
url_value_preprocessor()but application wide.
-
before_app_first_request(f)[source]¶ Like
Flask.before_first_request(). Such a function is executed before the first request to the application.
-
before_app_request(f)[source]¶ Like
Flask.before_request(). Such a function is executed before each request, even if outside of a blueprint.
-
before_request(f)[source]¶ 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)[source]¶ Like
Flask.context_processor()but for a blueprint. This function is only executed for requests handled by a blueprint.
-
endpoint(endpoint)[source]¶ 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)[source]¶ 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 theFlaskobject.
-
make_setup_state(app, options, first_registration=False)[source]¶ 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.
-
record(func)[source]¶ 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)[source]¶ 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)[source]¶ 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.
-
register_error_handler(code_or_exception, f)[source]¶ Non-decorator version of the
errorhandler()error attach function, akin to theregister_error_handler()application-wide function of theFlaskobject but for error handlers limited to this blueprint.New in version 0.11.
-
route(rule, **options)[source]¶ Like
Flask.route()but for a blueprint. The endpoint for theurl_for()function is prefixed with the name of the blueprint.
-
teardown_app_request(f)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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.
-
warn_on_modifications= False¶
-
-
class
flask.blueprints.BlueprintSetupState(blueprint, app, options, first_registration)[source]¶ Bases:
objectTemporary holder object for registering a blueprint with the application. An instance of this class is created by the
make_setup_state()method and later passed to all register callback functions.-
add_url_rule(rule, endpoint=None, view_func=None, **options)[source]¶ A helper method to register a rule (and optionally a view function) to the application. The endpoint is automatically prefixed with the blueprint’s name.
-
app= None¶ a reference to the current application
-
blueprint= None¶ a reference to the blueprint that created this setup state.
-
first_registration= None¶ as blueprints can be registered multiple times with the application and not everything wants to be registered multiple times on it, this attribute can be used to figure out if the blueprint was registered in the past already.
-
options= None¶ a dictionary with all options that were passed to the
register_blueprint()method.
-
subdomain= None¶ The subdomain that the blueprint should be active for,
Noneotherwise.
-
url_defaults= None¶ A dictionary with URL defaults that is added to each and every URL that was defined with the blueprint.
-
url_prefix= None¶ The prefix that should be used for all URLs defined on the blueprint.
-
flask.cli module¶
flask.cli¶
A simple command line application to run flask apps.
| copyright: |
|
|---|---|
| license: | BSD, see LICENSE for more details. |
-
class
flask.cli.AppGroup(name=None, commands=None, **attrs)[source]¶ Bases:
click.core.GroupThis works similar to a regular click
Groupbut it changes the behavior of thecommand()decorator so that it automatically wraps the functions inwith_appcontext().Not to be confused with
FlaskGroup.-
command(*args, **kwargs)[source]¶ This works exactly like the method of the same name on a regular
click.Groupbut it wraps callbacks inwith_appcontext()unless it’s disabled by passingwith_appcontext=False.
-
-
class
flask.cli.DispatchingApp(loader, use_eager_loading=False)[source]¶ Bases:
objectSpecial application that dispatches to a flask application which is imported by name in a background thread. If an error happens it is is recorded and shows as part of the WSGI handling which in case of the Werkzeug debugger means that it shows up in the browser.
-
class
flask.cli.FlaskGroup(add_default_commands=True, create_app=None, **extra)[source]¶ Bases:
flask.cli.AppGroupSpecial subclass of the
AppGroupgroup that supports loading more commands from the configured Flask app. Normally a developer does not have to interface with this class but there are some very advanced use cases for which it makes sense to create an instance of this.For information as of why this is useful see custom-scripts.
Parameters: - add_default_commands – if this is True then the default run and shell commands wil be added.
- create_app – an optional callback that is passed the script info and returns the loaded app.
-
exception
flask.cli.NoAppException(message, ctx=None)[source]¶ Bases:
click.exceptions.UsageErrorRaised if an application cannot be found or loaded.
-
class
flask.cli.ScriptInfo(app_import_path=None, create_app=None)[source]¶ Bases:
objectHelp object to deal with Flask applications. This is usually not necessary to interface with as it’s used internally in the dispatching to click. In future versions of Flask this object will most likely play a bigger role. Typically it’s created automatically by the
FlaskGroupbut you can also manually create it and pass it onwards as click object.-
app_import_path= None¶ Optionally the import path for the Flask application.
-
create_app= None¶ Optionally a function that is passed the script info to create the instance of the application.
-
data= None¶ A dictionary with arbitrary data that can be associated with this script info.
-
-
flask.cli.find_best_app(module)[source]¶ Given a module instance this tries to find the best possible application in the module or raises an exception.
flask.config module¶
flask.config¶
Implements the configuration related objects.
| copyright: |
|
|---|---|
| license: | BSD, see LICENSE for more details. |
-
class
flask.config.Config(root_path, defaults=None)[source]¶ Bases:
dictWorks exactly like a dict but provides ways to fill it from files or special dictionaries. There are two common patterns to populate the config.
Either you can fill the config from a config file:
app.config.from_pyfile('yourconfig.cfg')
Or alternatively you can define the configuration options in the module that calls
from_object()or provide an import path to a module that should be loaded. It is also possible to tell it to use the same module and with that provide the configuration values just before the call:DEBUG = True SECRET_KEY = 'development key' app.config.from_object(__name__)
In both cases (loading from any Python file or loading from modules), only uppercase keys are added to the config. This makes it possible to use lowercase values in the config file for temporary values that are not added to the config or to define the config keys in the same file that implements the application.
Probably the most interesting way to load configurations is from an environment variable pointing to a file:
app.config.from_envvar('YOURAPPLICATION_SETTINGS')
In this case before launching the application you have to set this environment variable to the file you want to use. On Linux and OS X use the export statement:
export YOURAPPLICATION_SETTINGS='/path/to/config/file'
On windows use set instead.
Parameters: - root_path – path to which files are read relative from. When the
config object is created by the application, this is
the application’s
root_path. - defaults – an optional dictionary of default values
-
from_envvar(variable_name, silent=False)[source]¶ Loads a configuration from an environment variable pointing to a configuration file. This is basically just a shortcut with nicer error messages for this line of code:
app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])
Parameters: - variable_name – name of the environment variable
- silent – set to
Trueif you want silent failure for missing files.
Returns: bool.
Trueif able to load config,Falseotherwise.
-
from_json(filename, silent=False)[source]¶ Updates the values in the config from a JSON file. This function behaves as if the JSON object was a dictionary and passed to the
from_mapping()function.Parameters: - filename – the filename of the JSON file. This can either be an absolute filename or a filename relative to the root path.
- silent – set to
Trueif you want silent failure for missing files.
New in version 0.11.
-
from_mapping(*mapping, **kwargs)[source]¶ Updates the config like
update()ignoring items with non-upper keys.New in version 0.11.
-
from_object(obj)[source]¶ Updates the values from the given object. An object can be of one of the following two types:
- a string: in this case the object with that name will be imported
- an actual object reference: that object is used directly
Objects are usually either modules or classes.
Just the uppercase variables in that object are stored in the config. Example usage:
app.config.from_object('yourapplication.default_config') from yourapplication import default_config app.config.from_object(default_config)
You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with
from_pyfile()and ideally from a location not within the package because the package might be installed system wide.Parameters: obj – an import name or object
-
from_pyfile(filename, silent=False)[source]¶ Updates the values in the config from a Python file. This function behaves as if the file was imported as module with the
from_object()function.Parameters: - filename – the filename of the config. This can either be an absolute filename or a filename relative to the root path.
- silent – set to
Trueif you want silent failure for missing files.
New in version 0.7: silent parameter.
-
get_namespace(namespace, lowercase=True, trim_namespace=True)[source]¶ Returns a dictionary containing a subset of configuration options that match the specified namespace/prefix. Example usage:
app.config['IMAGE_STORE_TYPE'] = 'fs' app.config['IMAGE_STORE_PATH'] = '/var/app/images' app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com' image_store_config = app.config.get_namespace('IMAGE_STORE_')
The resulting dictionary image_store_config would look like:
{ 'type': 'fs', 'path': '/var/app/images', 'base_url': 'http://img.website.com' }
This is often useful when configuration options map directly to keyword arguments in functions or class constructors.
Parameters: - namespace – a configuration namespace
- lowercase – a flag indicating if the keys of the resulting dictionary should be lowercase
- trim_namespace – a flag indicating if the keys of the resulting dictionary should not include the namespace
New in version 0.11.
- root_path – path to which files are read relative from. When the
config object is created by the application, this is
the application’s
flask.ctx module¶
flask.ctx¶
Implements the objects required to keep the context.
| copyright: |
|
|---|---|
| license: | BSD, see LICENSE for more details. |
-
class
flask.ctx.AppContext(app)[source]¶ Bases:
objectThe application context binds an application object implicitly to the current thread or greenlet, similar to how the
RequestContextbinds request information. The application context is also implicitly created if a request context is created but the application is not on top of the individual application context.
-
class
flask.ctx.RequestContext(app, environ, request=None)[source]¶ Bases:
objectThe request context contains all request relevant information. It is created at the beginning of the request and pushed to the _request_ctx_stack and removed at the end of it. It will create the URL adapter and request object for the WSGI environment provided.
Do not attempt to use this class directly, instead use
test_request_context()andrequest_context()to create this object.When the request context is popped, it will evaluate all the functions registered on the application for teardown execution (
teardown_request()).The request context is automatically popped at the end of the request for you. In debug mode the request context is kept around if exceptions happen so that interactive debuggers have a chance to introspect the data. With 0.4 this can also be forced for requests that did not fail and outside of
DEBUGmode. By setting'flask._preserve_context'toTrueon the WSGI environment the context will not pop itself at the end of the request. This is used by thetest_client()for example to implement the deferred cleanup functionality.You might find this helpful for unittests where you need the information from the context local around for a little longer. Make sure to properly
pop()the stack yourself in that situation, otherwise your unittests will leak memory.-
copy()[source]¶ Creates a copy of this request context with the same request object. This can be used to move a request context to a different greenlet. Because the actual request object is the same this cannot be used to move a request context to a different thread unless access to the request object is locked.
New in version 0.10.
-
g¶
-
-
flask.ctx.after_this_request(f)[source]¶ Executes a function after this request. This is useful to modify response objects. The function is passed the response object and has to return the same or a new one.
Example:
@app.route('/') def index(): @after_this_request def add_header(response): response.headers['X-Foo'] = 'Parachute' return response return 'Hello World!'
This is more useful if a function other than the view function wants to modify a response. For instance think of a decorator that wants to add some headers without converting the return value into a response object.
New in version 0.9.
-
flask.ctx.copy_current_request_context(f)[source]¶ A helper function that decorates a function to retain the current request context. This is useful when working with greenlets. The moment the function is decorated a copy of the request context is created and then pushed when the function is called.
Example:
import gevent from flask import copy_current_request_context @app.route('/') def index(): @copy_current_request_context def do_some_work(): # do some work here, it can access flask.request like you # would otherwise in the view function. ... gevent.spawn(do_some_work) return 'Regular response'
New in version 0.10.
-
flask.ctx.has_app_context()[source]¶ Works like
has_request_context()but for the application context. You can also just do a boolean check on thecurrent_appobject instead.New in version 0.9.
-
flask.ctx.has_request_context()[source]¶ If you have code that wants to test if a request context is there or not this function can be used. For instance, you may want to take advantage of request information if the request object is available, but fail silently if it is unavailable.
class User(db.Model): def __init__(self, username, remote_addr=None): self.username = username if remote_addr is None and has_request_context(): remote_addr = request.remote_addr self.remote_addr = remote_addr
Alternatively you can also just test any of the context bound objects (such as
requestorgfor truthness):class User(db.Model): def __init__(self, username, remote_addr=None): self.username = username if remote_addr is None and request: remote_addr = request.remote_addr self.remote_addr = remote_addr
New in version 0.7.
flask.debughelpers module¶
flask.debughelpers¶
Various helpers to make the development experience better.
| copyright: |
|
|---|---|
| license: | BSD, see LICENSE for more details. |
-
exception
flask.debughelpers.DebugFilesKeyError(request, key)[source]¶ Bases:
KeyError,AssertionErrorRaised from request.files during debugging. The idea is that it can provide a better error message than just a generic KeyError/BadRequest.
-
exception
flask.debughelpers.FormDataRoutingRedirect(request)[source]¶ Bases:
AssertionErrorThis exception is raised by Flask in debug mode if it detects a redirect caused by the routing system when the request method is not GET, HEAD or OPTIONS. Reasoning: form data will be dropped.
-
exception
flask.debughelpers.UnexpectedUnicodeError[source]¶ Bases:
AssertionError,UnicodeErrorRaised in places where we want some better error reporting for unexpected unicode or binary data.
flask.exthook module¶
flask.exthook¶
Redirect imports for extensions. This module basically makes it possible for us to transition from flaskext.foo to flask_foo without having to force all extensions to upgrade at the same time.
When a user does from flask.ext.foo import bar it will attempt to
import from flask_foo import bar first and when that fails it will
try to import from flaskext.foo import bar.
We’re switching from namespace packages because it was just too painful for everybody involved.
This is used by flask.ext.
| copyright: |
|
|---|---|
| license: | BSD, see LICENSE for more details. |
-
class
flask.exthook.ExtensionImporter(module_choices, wrapper_module)[source]¶ Bases:
objectThis importer redirects imports from this submodule to other locations. This makes it possible to transition from the old flaskext.name to the newer flask_name without people having a hard time.
-
is_important_traceback(important_module, tb)[source]¶ Walks a traceback’s frames and checks if any of the frames originated in the given important module. If that is the case then we were able to import the module itself but apparently something went wrong when the module was imported. (Eg: import of an import failed).
-
flask.globals module¶
flask.globals¶
Defines all the global objects that are proxies to the current active context.
| copyright: |
|
|---|---|
| license: | BSD, see LICENSE for more details. |
flask.helpers module¶
flask.helpers¶
Implements various helpers.
| copyright: |
|
|---|---|
| license: | BSD, see LICENSE for more details. |
-
flask.helpers.find_package(import_name)[source]¶ Finds a package and returns the prefix (or None if the package is not installed) as well as the folder that contains the package or module as a tuple. The package path returned is the module that would have to be added to the pythonpath in order to make it possible to import the module. The prefix is the path below which a UNIX like folder structure exists (lib, share etc.).
-
flask.helpers.flash(message, category='message')[source]¶ Flashes a message to the next request. In order to remove the flashed message from the session and to display it to the user, the template has to call
get_flashed_messages().Changed in version 0.3: category parameter added.
Parameters: - message – the message to be flashed.
- category – the category for the message. The following values
are recommended:
'message'for any kind of message,'error'for errors,'info'for information messages and'warning'for warnings. However any kind of string can be used as category.
-
flask.helpers.get_flashed_messages(with_categories=False, category_filter=[])[source]¶ Pulls all flashed messages from the session and returns them. Further calls in the same request to the function will return the same messages. By default just the messages are returned, but when with_categories is set to
True, the return value will be a list of tuples in the form(category, message)instead.Filter the flashed messages to one or more categories by providing those categories in category_filter. This allows rendering categories in separate html blocks. The with_categories and category_filter arguments are distinct:
- with_categories controls whether categories are returned with message
text (
Truegives a tuple, whereFalsegives just the message text). - category_filter filters the messages down to only those matching the provided categories.
See message-flashing-pattern for examples.
Changed in version 0.3: with_categories parameter added.
Changed in version 0.9: category_filter parameter added.
Parameters: - with_categories – set to
Trueto also receive categories. - category_filter – whitelist of categories to limit return values
- with_categories controls whether categories are returned with message
text (
-
flask.helpers.get_root_path(import_name)[source]¶ Returns the path to a package or cwd if that cannot be found. This returns the path of a package or the folder that contains a module.
Not to be confused with the package path returned by
find_package().
-
flask.helpers.get_template_attribute(template_name, attribute)[source]¶ Loads a macro (or variable) a template exports. This can be used to invoke a macro from within Python code. If you for example have a template named
_cider.htmlwith the following contents:{% macro hello(name) %}Hello {{ name }}!{% endmacro %}
You can access this from Python code like this:
hello = get_template_attribute('_cider.html', 'hello') return hello('World')
New in version 0.2.
Parameters: - template_name – the name of the template
- attribute – the name of the variable of macro to access
-
class
flask.helpers.locked_cached_property(func, name=None, doc=None)[source]¶ Bases:
objectA decorator that converts a function into a lazy property. The function wrapped is called the first time to retrieve the result and then that calculated result is used the next time you access the value. Works like the one in Werkzeug but has a lock for thread safety.
-
flask.helpers.make_response(*args)[source]¶ Sometimes it is necessary to set additional headers in a view. Because views do not have to return response objects but can return a value that is converted into a response object by Flask itself, it becomes tricky to add headers to it. This function can be called instead of using a return and you will get a response object which you can use to attach headers.
If view looked like this and you want to add a new header:
def index(): return render_template('index.html', foo=42)
You can now do something like this:
def index(): response = make_response(render_template('index.html', foo=42)) response.headers['X-Parachutes'] = 'parachutes are cool' return response
This function accepts the very same arguments you can return from a view function. This for example creates a response with a 404 error code:
response = make_response(render_template('not_found.html'), 404)
The other use case of this function is to force the return value of a view function into a response which is helpful with view decorators:
response = make_response(view_function()) response.headers['X-Parachutes'] = 'parachutes are cool'
Internally this function does the following things:
- if no arguments are passed, it creates a new response argument
- if one argument is passed,
flask.Flask.make_response()is invoked with it. - if more than one argument is passed, the arguments are passed
to the
flask.Flask.make_response()function as tuple.
New in version 0.6.
-
flask.helpers.safe_join(directory, filename)[source]¶ Safely join directory and filename.
Example usage:
@app.route('/wiki/<path:filename>') def wiki_page(filename): filename = safe_join(app.config['WIKI_FOLDER'], filename) with open(filename, 'rb') as fd: content = fd.read() # Read and process the file content...
Parameters: - directory – the base directory.
- filename – the untrusted filename relative to that directory.
Raises: NotFoundif the resulting path would fall out of directory.
-
flask.helpers.send_file(filename_or_fp, mimetype=None, as_attachment=False, attachment_filename=None, add_etags=True, cache_timeout=None, conditional=False)[source]¶ Sends the contents of a file to the client. This will use the most efficient method available and configured. By default it will try to use the WSGI server’s file_wrapper support. Alternatively you can set the application’s
use_x_sendfileattribute toTrueto directly emit anX-Sendfileheader. This however requires support of the underlying webserver forX-Sendfile.By default it will try to guess the mimetype for you, but you can also explicitly provide one. For extra security you probably want to send certain files as attachment (HTML for instance). The mimetype guessing requires a filename or an attachment_filename to be provided.
Please never pass filenames to this function from user sources; you should use
send_from_directory()instead.New in version 0.2.
New in version 0.5: The add_etags, cache_timeout and conditional parameters were added. The default behavior is now to attach etags.
Changed in version 0.7: mimetype guessing and etag support for file objects was deprecated because it was unreliable. Pass a filename if you are able to, otherwise attach an etag yourself. This functionality will be removed in Flask 1.0
Changed in version 0.9: cache_timeout pulls its default from application config, when None.
Parameters: - filename_or_fp – the filename of the file to send in latin-1.
This is relative to the
root_pathif a relative path is specified. Alternatively a file object might be provided in which caseX-Sendfilemight not work and fall back to the traditional method. Make sure that the file pointer is positioned at the start of data to send before callingsend_file(). - mimetype – the mimetype of the file if provided, otherwise auto detection happens.
- as_attachment – set to
Trueif you want to send this file with aContent-Disposition: attachmentheader. - attachment_filename – the filename for the attachment if it differs from the file’s filename.
- add_etags – set to
Falseto disable attaching of etags. - conditional – set to
Trueto enable conditional responses. - cache_timeout – the timeout in seconds for the headers. When
None(default), this value is set byget_send_file_max_age()ofcurrent_app.
- filename_or_fp – the filename of the file to send in latin-1.
This is relative to the
-
flask.helpers.send_from_directory(directory, filename, **options)[source]¶ Send a file from a given directory with
send_file(). This is a secure way to quickly expose static files from an upload folder or something similar.Example usage:
@app.route('/uploads/<path:filename>') def download_file(filename): return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True)
Sending files and Performance
It is strongly recommended to activate either
X-Sendfilesupport in your webserver or (if no authentication happens) to tell the webserver to serve files for the given path on its own without calling into the web application for improved performance.New in version 0.5.
Parameters: - directory – the directory where all the files are stored.
- filename – the filename relative to that directory to download.
- options – optional keyword arguments that are directly
forwarded to
send_file().
-
flask.helpers.stream_with_context(generator_or_function)[source]¶ Request contexts disappear when the response is started on the server. This is done for efficiency reasons and to make it less likely to encounter memory leaks with badly written WSGI middlewares. The downside is that if you are using streamed responses, the generator cannot access request bound information any more.
This function however can help you keep the context around for longer:
from flask import stream_with_context, request, Response @app.route('/stream') def streamed_response(): @stream_with_context def generate(): yield 'Hello ' yield request.args['name'] yield '!' return Response(generate())
Alternatively it can also be used around a specific generator:
from flask import stream_with_context, request, Response @app.route('/stream') def streamed_response(): def generate(): yield 'Hello ' yield request.args['name'] yield '!' return Response(stream_with_context(generate()))
New in version 0.9.
-
flask.helpers.total_seconds(td)[source]¶ Returns the total seconds from a timedelta object.
Parameters: td (timedelta) – the timedelta to be converted in seconds Returns: number of seconds Return type: int
-
flask.helpers.url_for(endpoint, **values)[source]¶ Generates a URL to the given endpoint with the method provided.
Variable arguments that are unknown to the target endpoint are appended to the generated URL as query arguments. If the value of a query argument is
None, the whole pair is skipped. In case blueprints are active you can shortcut references to the same blueprint by prefixing the local endpoint with a dot (.).This will reference the index function local to the current blueprint:
url_for('.index')
For more information, head over to the Quickstart.
To integrate applications,
Flaskhas a hook to intercept URL build errors throughFlask.url_build_error_handlers. The url_for function results in aBuildErrorwhen the current app does not have a URL for the given endpoint and values. When it does, thecurrent_appcalls itsurl_build_error_handlersif it is notNone, which can return a string to use as the result of url_for (instead of url_for‘s default to raise theBuildErrorexception) or re-raise the exception. An example:def external_url_handler(error, endpoint, values): "Looks up an external URL when `url_for` cannot build a URL." # This is an example of hooking the build_error_handler. # Here, lookup_url is some utility function you've built # which looks up the endpoint in some external URL registry. url = lookup_url(endpoint, **values) if url is None: # External lookup did not have a URL. # Re-raise the BuildError, in context of original traceback. exc_type, exc_value, tb = sys.exc_info() if exc_value is error: raise exc_type, exc_value, tb else: raise error # url_for will use this result, instead of raising BuildError. return url app.url_build_error_handlers.append(external_url_handler)
Here, error is the instance of
BuildError, and endpoint and values are the arguments passed into url_for. Note that this is for building URLs outside the current application, and not for handling 404 NotFound errors.New in version 0.10: The _scheme parameter was added.
New in version 0.9: The _anchor and _method parameters were added.
New in version 0.9: Calls
Flask.handle_build_error()onBuildError.Parameters: - endpoint – the endpoint of the URL (name of the function)
- values – the variable arguments of the URL rule
- _external – if set to
True, an absolute URL is generated. Server address can be changed viaSERVER_NAMEconfiguration variable which defaults to localhost. - _scheme – a string specifying the desired URL scheme. The _external
parameter must be set to
Trueor aValueErroris raised. The default behavior uses the same scheme as the current request, orPREFERRED_URL_SCHEMEfrom the app configuration if no request context is available. As of Werkzeug 0.10, this also can be set to an empty string to build protocol-relative URLs. - _anchor – if provided this is added as anchor to the URL.
- _method – if provided this explicitly specifies an HTTP method.
flask.json module¶
flask.jsonimpl¶
Implementation helpers for the JSON support in Flask.
| copyright: |
|
|---|---|
| license: | BSD, see LICENSE for more details. |
-
flask.json.dumps(obj, **kwargs)[source]¶ Serialize
objto a JSON formattedstrby using the application’s configured encoder (json_encoder) if there is an application on the stack.This function can return
unicodestrings or ascii-only bytestrings by default which coerce into unicode strings automatically. That behavior by default is controlled by theJSON_AS_ASCIIconfiguration variable and can be overridden by the simplejsonensure_asciiparameter.
-
flask.json.loads(s, **kwargs)[source]¶ Unserialize a JSON object from a string
sby using the application’s configured decoder (json_decoder) if there is an application on the stack.
-
flask.json.htmlsafe_dump(obj, fp, **kwargs)[source]¶ Like
htmlsafe_dumps()but writes into a file object.
-
flask.json.htmlsafe_dumps(obj, **kwargs)[source]¶ Works exactly like
dumps()but is safe for use in<script>tags. It accepts the same arguments and returns a JSON string. Note that this is available in templates through the|tojsonfilter which will also mark the result as safe. Due to how this function escapes certain characters this is safe even if used outside of<script>tags.The following characters are escaped in strings:
<>&'
This makes it safe to embed such strings in any place in HTML with the notable exception of double quoted attributes. In that case single quote your attributes or HTML escape it in addition.
Changed in version 0.10: This function’s return value is now always safe for HTML usage, even if outside of script tags or if used in XHTML. This rule does not hold true when using this function in HTML attributes that are double quoted. Always single quote attributes if you use the
|tojsonfilter. Alternatively use|tojson|forceescape.
-
class
flask.json.JSONDecoder(encoding=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None)[source]¶ Bases:
simplejson.decoder.JSONDecoderThe default JSON decoder. This one does not change the behavior from the default simplejson decoder. Consult the
jsondocumentation for more information. This decoder is not only used for the load functions of this module but alsoRequest.
-
class
flask.json.JSONEncoder(skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False)[source]¶ Bases:
simplejson.encoder.JSONEncoderThe default Flask JSON encoder. This one extends the default simplejson encoder by also supporting
datetimeobjects,UUIDas well asMarkupobjects which are serialized as RFC 822 datetime strings (same as the HTTP date format). In order to support more data types override thedefault()method.-
default(o)[source]¶ Implement this method in a subclass such that it returns a serializable object for
o, or calls the base implementation (to raise aTypeError).For example, to support arbitrary iterators, you could implement default like this:
def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, o)
-
-
flask.json.jsonify(*args, **kwargs)[source]¶ This function wraps
dumps()to add a few enhancements that make life easier. It turns the JSON output into aResponseobject with the application/json mimetype. For convenience, it also converts multiple arguments into an array or multiple keyword arguments into a dict. This means that bothjsonify(1,2,3)andjsonify([1,2,3])serialize to[1,2,3].For clarity, the JSON serialization behavior has the following differences from
dumps():- Single argument: Passed straight through to
dumps(). - Multiple arguments: Converted to an array before being passed to
dumps(). - Multiple keyword arguments: Converted to a dict before being passed to
dumps(). - Both args and kwargs: Behavior undefined and will throw an exception.
Example usage:
from flask import jsonify @app.route('/_get_current_user') def get_current_user(): return jsonify(username=g.user.username, email=g.user.email, id=g.user.id)
This will send a JSON response like this to the browser:
{ "username": "admin", "email": "admin@localhost", "id": 42 }
Changed in version 0.11: Added support for serializing top-level arrays. This introduces a security risk in ancient browsers. See json-security for details.
This function’s response will be pretty printed if it was not requested with
X-Requested-With: XMLHttpRequestto simplify debugging unless theJSONIFY_PRETTYPRINT_REGULARconfig parameter is set to false. Compressed (not pretty) formatting currently means no indents and no spaces after separators.New in version 0.2.
- Single argument: Passed straight through to
flask.logging module¶
flask.logging¶
Implements the logging support for Flask.
| copyright: |
|
|---|---|
| license: | BSD, see LICENSE for more details. |
-
flask.logging.create_logger(app)[source]¶ Creates a logger for the given application. This logger works similar to a regular Python logger but changes the effective logging level based on the application’s debug flag. Furthermore this function also removes all attached handlers in case there was a logger with the log name before.
flask.sessions module¶
flask.sessions¶
Implements cookie based sessions based on itsdangerous.
| copyright: |
|
|---|---|
| license: | BSD, see LICENSE for more details. |
-
class
flask.sessions.NullSession(initial=None)[source]¶ Bases:
flask.sessions.SecureCookieSessionClass 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.
-
clear(*args, **kwargs)¶
-
pop(*args, **kwargs)¶
-
popitem(*args, **kwargs)¶
-
setdefault(*args, **kwargs)¶
-
update(*args, **kwargs)¶
-
-
class
flask.sessions.SecureCookieSession(initial=None)[source]¶ Bases:
werkzeug.datastructures.CallbackDict,flask.sessions.SessionMixinBase class for sessions based on signed cookies.
-
class
flask.sessions.SecureCookieSessionInterface[source]¶ Bases:
flask.sessions.SessionInterfaceThe default session interface that stores sessions in signed cookies through the
itsdangerousmodule.-
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 at 0x000001E1821A4C18>¶ 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.SessionInterface[source]¶ Bases:
objectThe 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()returnsNoneFlask 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 defaultNullSessionclass 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_HTTPONLYconfig var.
Returns the path for which the cookie should be valid. The default implementation uses the value from the
SESSION_COOKIE_PATHconfig var if it’s set, and falls back toAPPLICATION_ROOTor uses/if it’sNone.
Returns True if the cookie should be secure. This currently just returns the value of the
SESSION_COOKIE_SECUREsetting.
-
get_expiration_time(app, session)[source]¶ A helper method that returns an expiration date for the session or
Noneif 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)[source]¶ 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_classby default.
-
make_null_session(app)[source]¶ 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_classby 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)[source]¶ This method has to be implemented and must either return
Nonein 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 onSessionMixin.
-
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)[source]¶ 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.
Indicates whether a cookie should be set now or not. This is used by session backends to figure out if they should emit a set-cookie header or not. The default behavior is controlled by the
SESSION_REFRESH_EACH_REQUESTconfig variable. If it’s set toFalsethen a cookie is only set if the session is modified, if set toTrueit’s always set if the session is permanent.This check is usually skipped if sessions get deleted.
New in version 0.11.
-
class
flask.sessions.SessionMixin[source]¶ Bases:
objectExpands 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 hardcodesTruein.
-
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
Falsein.
-
permanent¶ this reflects the
'_permanent'key in the dict.
-
flask.signals module¶
flask.templating module¶
flask.templating¶
Implements the bridge to Jinja2.
| copyright: |
|
|---|---|
| license: | BSD, see LICENSE for more details. |
-
class
flask.templating.DispatchingJinjaLoader(app)[source]¶ Bases:
jinja2.loaders.BaseLoaderA loader that looks for templates in the application and all the blueprint folders.
-
class
flask.templating.Environment(app, **options)[source]¶ Bases:
jinja2.environment.EnvironmentWorks like a regular Jinja2 environment but has some additional knowledge of how Flask’s blueprint works so that it can prepend the name of the blueprint to referenced templates if necessary.
-
flask.templating.render_template(template_name_or_list, **context)[source]¶ Renders a template from the template folder with the given context.
Parameters: - template_name_or_list – the name of the template to be rendered, or an iterable with template names the first one existing will be rendered
- context – the variables that should be available in the context of the template.
-
flask.templating.render_template_string(source, **context)[source]¶ Renders a template from the given template source string with the given context. Template variables will be autoescaped.
Parameters: - source – the source code of the template to be rendered
- context – the variables that should be available in the context of the template.
flask.testing module¶
flask.testing¶
Implements test support helpers. This module is lazily imported and usually not used in production environments.
| copyright: |
|
|---|---|
| license: | BSD, see LICENSE for more details. |
-
class
flask.testing.FlaskClient(application, response_wrapper=None, use_cookies=True, allow_subdomain_redirects=False)[source]¶ Bases:
werkzeug.test.ClientWorks 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
withbody when used in awithstatement. For general information about how to use this class refer towerkzeug.test.Client.Basic usage is outlined in the testing chapter.
-
preserve_context= False¶
-
session_transaction(*args, **kwargs)[source]¶ When used in combination with a
withstatement this opens a session transaction. This can be used to modify the session that the test client uses. Once thewithblock 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.
-
flask.views module¶
flask.views¶
This module provides class-based views inspired by the ones in Django.
| copyright: |
|
|---|---|
| license: | BSD, see LICENSE for more details. |
-
class
flask.views.MethodView[source]¶ Bases:
flask.views.ViewLike a regular class-based view but that dispatches requests to particular methods. For instance if you implement a method called
get()it means you will response to'GET'requests and thedispatch_request()implementation will automatically forward your request to that. Alsooptionsis set for you automatically:class CounterAPI(MethodView): def get(self): return session.get('counter', 0) def post(self): session['counter'] = session.get('counter', 0) + 1 return 'OK' app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))
-
class
flask.views.View[source]¶ Bases:
objectAlternative way to use view functions. A subclass has to implement
dispatch_request()which is called with the view arguments from the URL routing system. Ifmethodsis provided the methods do not have to be passed to theadd_url_rule()method explicitly:class MyView(View): methods = ['GET'] def dispatch_request(self, name): return 'Hello %s!' % name app.add_url_rule('/hello/<name>', view_func=MyView.as_view('myview'))
When you want to decorate a pluggable view you will have to either do that when the view function is created (by wrapping the return value of
as_view()) or you can use thedecoratorsattribute:class SecretView(View): methods = ['GET'] decorators = [superuser_required] def dispatch_request(self): ...
The decorators stored in the decorators list are applied one after another when the view function is created. Note that you can not use the class based decorators since those would decorate the view class and not the generated view function!
-
classmethod
as_view(name, *class_args, **class_kwargs)[source]¶ Converts the class into an actual view function that can be used with the routing system. Internally this generates a function on the fly which will instantiate the
Viewon each request and call thedispatch_request()method on it.The arguments passed to
as_view()are forwarded to the constructor of the class.
-
decorators= ()¶ The canonical way to decorate class-based views is to decorate the return value of as_view(). However since this moves parts of the logic from the class declaration to the place where it’s hooked into the routing system.
You can place one or more decorators in this list and whenever the view function is created the result is automatically decorated.
New in version 0.8.
-
dispatch_request()[source]¶ Subclasses have to override this method to implement the actual view function code. This method is called with all the arguments from the URL rule.
-
methods= None¶ A list of methods this view can handle.
-
classmethod
flask.wrappers module¶
flask.wrappers¶
Implements the WSGI wrappers (request and response).
| copyright: |
|
|---|---|
| license: | BSD, see LICENSE for more details. |
-
class
flask.wrappers.Request(environ, populate_request=True, shallow=False)[source]¶ Bases:
werkzeug.wrappers.RequestThe 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_classto your subclass.The request object is a
Requestsubclass and provides all of the attributes Werkzeug defines plus a few Flask specific ones.-
blueprint¶ The name of the current blueprint
-
endpoint¶ The endpoint that matched the request. This in combination with
view_argscan be used to reconstruct the same or a modified URL. If an exception happened when matching, this will beNone.
-
get_json(force=False, silent=False, cache=True)[source]¶ Parses the incoming JSON request data and returns it. By default this function will return
Noneif the mimetype is not application/json but this can be overridden by theforceparameter. If parsing fails theon_json_loading_failed()method on the request object will be invoked.Parameters: - force – if set to
Truethe mimetype is ignored. - silent – if set to
Truethis method will fail silently and returnNone. - cache – if set to
Truethe parsed JSON data is remembered on the request.
- force – if set to
-
is_json¶ Indicates if this request is JSON or not. By default a request is considered to include JSON data if the mimetype is application/json or application/*+json.
New in version 0.11.
-
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_LENGTHconfig 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)[source]¶ 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 aBadRequestexception.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
NotFoundexception 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.wrappers.Response(response=None, status=None, headers=None, mimetype=None, content_type=None, direct_passthrough=False)[source]¶ Bases:
werkzeug.wrappers.ResponseThe 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_classto your subclass.-
default_mimetype= 'text/html'¶
-