doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
do_teardown_request(exc=<object object>) Called after the request is dispatched and the response is returned, right before the request context is popped. This calls all functions decorated with teardown_request(), and Blueprint.teardown_request() if a blueprint handled the request. Finally, the request_tearing_down signal is sent. This is called by RequestContext.pop(), which may be delayed during testing to maintain access to resources. Parameters exc (Optional[BaseException]) – An unhandled exception raised while dispatching the request. Detected from the current exception information if not passed. Passed to each teardown function. Return type None Changelog Changed in version 0.9: Added the exc argument.
flask.api.index#flask.Flask.do_teardown_request
endpoint(endpoint) Decorate a view function to register it for the given endpoint. Used if a rule is added without a view_func with add_url_rule(). app.add_url_rule("/ex", endpoint="example") @app.endpoint("example") def example(): ... Parameters endpoint (str) – The endpoint name to associate with the view function. Return type Callable
flask.api.index#flask.Flask.endpoint
ensure_sync(func) Ensure that the function is synchronous for WSGI workers. Plain def functions are returned as-is. async def functions are wrapped to run and wait for the response. Override this method to change how the app runs async views. New in version 2.0. Parameters func (Callable) – Return type Callable
flask.api.index#flask.Flask.ensure_sync
env What environment the app is running in. Flask and extensions may enable behaviors based on the environment, such as enabling debug mode. This maps to the ENV config key. This is set by the FLASK_ENV environment variable and may not behave as expected if set in code. Do not enable development when deploying in production. Default: 'production'
flask.api.index#flask.Flask.env
errorhandler(code_or_exception) Register a function to handle errors by code or exception class. A decorator that is used to register a function given an error code. Example: @app.errorhandler(404) def page_not_found(error): return 'This page does not exist', 404 You can also register handlers for arbitrary exceptions: @app.errorhandler(DatabaseError) def special_exception_handler(error): return 'Database connection failed', 500 Changelog New in version 0.7: Use register_error_handler() instead of modifying error_handler_spec directly, 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 HTTPException class. Parameters code_or_exception (Union[Type[Exception], int]) – the code as integer for the handler, or an arbitrary exception Return type Callable
flask.api.index#flask.Flask.errorhandler
error_handler_spec: t.Dict[AppOrBlueprintKey, t.Dict[t.Optional[int], t.Dict[t.Type[Exception], ErrorHandlerCallable]]] A data structure of registered error handlers, in the format {scope: {code: {class: handler}}}`. The scope key is the name of a blueprint the handlers are active for, or None for all requests. The code key is the HTTP status code for HTTPException, or None for other exceptions. The innermost dictionary maps exception classes to handler functions. To register an error handler, use the errorhandler() decorator. This data structure is internal. It should not be modified directly and its format may change at any time.
flask.api.index#flask.Flask.error_handler_spec
extensions: dict a place where extensions can store application specific state. For example this is where an extension could store database engines and similar things. The key must match the name of the extension module. For example in case of a “Flask-Foo” extension in flask_foo, the key would be 'foo'. Changelog New in version 0.7.
flask.api.index#flask.Flask.extensions
full_dispatch_request() Dispatches the request and on top of that performs request pre and postprocessing as well as HTTP exception catching and error handling. Changelog New in version 0.7. Return type flask.wrappers.Response
flask.api.index#flask.Flask.full_dispatch_request
flask.g A namespace object that can store data during an application context. This is an instance of Flask.app_ctx_globals_class, which defaults to ctx._AppCtxGlobals. This is a good place to store resources during a request. During testing, you can use the Faking Resources and Context pattern to pre-configure such resources. This is a proxy. See Notes On Proxies for more information. Changelog Changed in version 0.10: Bound to the application context instead of the request context.
flask.api.index#flask.g
get(rule, **options) Shortcut for route() with methods=["GET"]. New in version 2.0. Parameters rule (str) – options (Any) – Return type Callable
flask.api.index#flask.Flask.get
get_send_file_max_age(filename) Used by send_file() to determine the max_age cache value for a given file path if it wasn’t passed. By default, this returns SEND_FILE_MAX_AGE_DEFAULT from the configuration of current_app. This defaults to None, which tells the browser to use conditional requests instead of a timed cache, which is usually preferable. Changed in version 2.0: The default configuration is None instead of 12 hours. Changelog New in version 0.9. Parameters filename (str) – Return type Optional[int]
flask.api.index#flask.Flask.get_send_file_max_age
flask.got_request_exception This signal is sent when an unhandled exception happens during request processing, including when debugging. The exception is passed to the subscriber as exception. This signal is not sent for HTTPException, or other exceptions that have error handlers registered, unless the exception was raised from an error handler. This example shows how to do some extra logging if a theoretical SecurityException was raised: from flask import got_request_exception def log_security_exception(sender, exception, **extra): if not isinstance(exception, SecurityException): return security_logger.exception( f"SecurityException at {request.url!r}", exc_info=exception, ) got_request_exception.connect(log_security_exception, app)
flask.api.index#flask.got_request_exception
handle_exception(e) Handle an exception that did not have an error handler associated with it, or that was raised from an error handler. This always causes a 500 InternalServerError. Always sends the got_request_exception signal. If propagate_exceptions is True, such as in debug mode, the error will be re-raised so that the debugger can display it. Otherwise, the original exception is logged, and an InternalServerError is returned. If an error handler is registered for InternalServerError or 500, it will be used. For consistency, the handler will always receive the InternalServerError. The original unhandled exception is available as e.original_exception. Changelog Changed in version 1.1.0: Always passes the InternalServerError instance to the handler, setting original_exception to the unhandled error. Changed in version 1.1.0: after_request functions and other finalization is done even for the default 500 response when there is no handler. New in version 0.3. Parameters e (Exception) – Return type flask.wrappers.Response
flask.api.index#flask.Flask.handle_exception
handle_http_exception(e) Handles an HTTP exception. By default this will invoke the registered error handlers and fall back to returning the exception as response. Changelog Changed in version 1.0.3: RoutingException, used internally for actions such as slash redirects during routing, is not passed to error handlers. Changed in version 1.0: Exceptions are looked up by code and by MRO, so HTTPExcpetion subclasses can be handled with a catch-all handler for the base HTTPException. New in version 0.3. Parameters e (werkzeug.exceptions.HTTPException) – Return type Union[werkzeug.exceptions.HTTPException, Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int, Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], WSGIApplication]
flask.api.index#flask.Flask.handle_http_exception
handle_url_build_error(error, endpoint, values) Handle BuildError on url_for(). Parameters error (Exception) – endpoint (str) – values (dict) – Return type str
flask.api.index#flask.Flask.handle_url_build_error
handle_user_exception(e) This method is called whenever an exception occurs that should be handled. A special case is HTTPException which is forwarded to the handle_http_exception() method. This function will either return a response value or reraise the exception with the same traceback. Changelog Changed in version 1.0: Key errors raised from request data like form show the bad key in debug mode rather than a generic bad request message. New in version 0.7. Parameters e (Exception) – Return type Union[werkzeug.exceptions.HTTPException, Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int, Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], WSGIApplication]
flask.api.index#flask.Flask.handle_user_exception
import_name The name of the package or module that this object belongs to. Do not change this once it is set by the constructor.
flask.api.index#flask.Flask.import_name
inject_url_defaults(endpoint, values) Injects the URL defaults for the given endpoint directly into the values dictionary passed. This is used internally and automatically called on URL building. Changelog New in version 0.7. Parameters endpoint (str) – values (dict) – Return type None
flask.api.index#flask.Flask.inject_url_defaults
instance_path Holds the path to the instance folder. Changelog New in version 0.8.
flask.api.index#flask.Flask.instance_path
iter_blueprints() Iterates over all blueprints by the order they were registered. Changelog New in version 0.11. Return type ValuesView[Blueprint]
flask.api.index#flask.Flask.iter_blueprints
jinja_environment alias of flask.templating.Environment
flask.api.index#flask.Flask.jinja_environment
jinja_options: dict = {} Options that are passed to the Jinja environment in create_jinja_environment(). Changing these options after the environment is created (accessing jinja_env) will have no effect. Changelog Changed in version 1.1.0: This is a dict instead of an ImmutableDict to allow easier configuration.
flask.api.index#flask.Flask.jinja_options
json_decoder alias of flask.json.JSONDecoder
flask.api.index#flask.Flask.json_decoder
json_encoder alias of flask.json.JSONEncoder
flask.api.index#flask.Flask.json_encoder
log_exception(exc_info) Logs an exception. This is called by handle_exception() if debugging is disabled and right before the handler is called. The default implementation logs the exception as error on the logger. Changelog New in version 0.8. Parameters exc_info (Union[Tuple[type, BaseException, types.TracebackType], Tuple[None, None, None]]) – Return type None
flask.api.index#flask.Flask.log_exception
make_config(instance_relative=False) Used to create the config attribute by the Flask constructor. The instance_relative parameter is passed in from the constructor of Flask (there named instance_relative_config) and indicates if the config should be relative to the instance path or the root path of the application. Changelog New in version 0.8. Parameters instance_relative (bool) – Return type flask.config.Config
flask.api.index#flask.Flask.make_config
make_default_options_response() This method is called to create the default OPTIONS response. This can be changed through subclassing to change the default behavior of OPTIONS responses. Changelog New in version 0.7. Return type flask.wrappers.Response
flask.api.index#flask.Flask.make_default_options_response
make_response(rv) Convert the return value from a view function to an instance of response_class. Parameters rv (Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], Union[Headers, Dict[str, Union[str, List[str], Tuple[str, ...]]], List[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int, Union[Headers, Dict[str, Union[str, List[str], Tuple[str, ...]]], List[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], WSGIApplication]) – the return value from the view function. The view function must return a response. Returning None, or the view ending without returning, is not allowed. The following types are allowed for view_rv: str A response object is created with the string encoded to UTF-8 as the body. bytes A response object is created with the bytes as the body. dict A dictionary that will be jsonify’d before being returned. tuple Either (body, status, headers), (body, status), or (body, headers), where body is any of the other types allowed here, status is a string or an integer, and headers is a dictionary or a list of (key, value) tuples. If body is a response_class instance, status overwrites the exiting value and headers are extended. response_class The object is returned unchanged. other Response class The object is coerced to response_class. callable() The function is called as a WSGI application. The result is used to create a response object. Return type flask.wrappers.Response Changelog Changed in version 0.9: Previously a tuple was interpreted as the arguments for the response object.
flask.api.index#flask.Flask.make_response
make_shell_context() Returns the shell context for an interactive shell for this application. This runs all the registered shell context processors. Changelog New in version 0.11. Return type dict
flask.api.index#flask.Flask.make_shell_context
flask.message_flashed This signal is sent when the application is flashing a message. The messages is sent as message keyword argument and the category as category. Example subscriber: recorded = [] def record(sender, message, category, **extra): recorded.append((message, category)) from flask import message_flashed message_flashed.connect(record, app) Changelog New in version 0.10.
flask.api.index#flask.message_flashed
open_instance_resource(resource, mode='rb') Opens a resource from the application’s instance folder (instance_path). Otherwise works like open_resource(). Instance resources can also be opened for writing. Parameters resource (str) – the name of the resource. To access resources within subfolders use forward slashes as separator. mode (str) – resource file opening mode, default is ‘rb’. Return type IO
flask.api.index#flask.Flask.open_instance_resource
open_resource(resource, mode='rb') Open a resource file relative to root_path for reading. For example, if the file schema.sql is next to the file app.py where the Flask app is defined, it can be opened with: with app.open_resource("schema.sql") as f: conn.executescript(f.read()) Parameters resource (str) – Path to the resource relative to root_path. mode (str) – Open the file in this mode. Only reading is supported, valid values are “r” (or “rt”) and “rb”. Return type IO
flask.api.index#flask.Flask.open_resource
patch(rule, **options) Shortcut for route() with methods=["PATCH"]. New in version 2.0. Parameters rule (str) – options (Any) – Return type Callable
flask.api.index#flask.Flask.patch
permanent_session_lifetime A timedelta which is used to set the expiration date of a permanent session. The default is 31 days which makes a permanent session survive for roughly one month. This attribute can also be configured from the config with the PERMANENT_SESSION_LIFETIME configuration key. Defaults to timedelta(days=31)
flask.api.index#flask.Flask.permanent_session_lifetime
post(rule, **options) Shortcut for route() with methods=["POST"]. New in version 2.0. Parameters rule (str) – options (Any) – Return type Callable
flask.api.index#flask.Flask.post
preprocess_request() Called before the request is dispatched. Calls url_value_preprocessors registered with the app and the current blueprint (if any). Then calls before_request_funcs registered with the app and the blueprint. If any before_request() handler returns a non-None value, the value is handled as if it was the return value from the view, and further request handling is stopped. Return type Optional[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int, Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], WSGIApplication]]
flask.api.index#flask.Flask.preprocess_request
process_response(response) Can be overridden in order to modify the response object before it’s sent to the WSGI server. By default this will call all the after_request() decorated functions. Changelog 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 (flask.wrappers.Response) – a response_class object. Returns a new response object or the same, has to be an instance of response_class. Return type flask.wrappers.Response
flask.api.index#flask.Flask.process_response
put(rule, **options) Shortcut for route() with methods=["PUT"]. New in version 2.0. Parameters rule (str) – options (Any) – Return type Callable
flask.api.index#flask.Flask.put
register_blueprint(blueprint, **options) Register a Blueprint on the application. Keyword arguments passed to this method will override the defaults set on the blueprint. Calls the blueprint’s register() method after recording the blueprint in the application’s blueprints. Parameters blueprint (Blueprint) – The blueprint to register. url_prefix – Blueprint routes will be prefixed with this. subdomain – Blueprint routes will match on this subdomain. url_defaults – Blueprint routes will use these default values for view arguments. options (Any) – Additional keyword arguments are passed to BlueprintSetupState. They can be accessed in record() callbacks. Return type None Changelog New in version 0.7.
flask.api.index#flask.Flask.register_blueprint
register_error_handler(code_or_exception, f) Alternative error attach function to the errorhandler() decorator that is more straightforward to use for non decorator usage. Changelog New in version 0.7. Parameters code_or_exception (Union[Type[Exception], int]) – f (Callable[[Exception], Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], Union[Headers, Dict[str, Union[str, List[str], Tuple[str, ...]]], List[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int, Union[Headers, Dict[str, Union[str, List[str], Tuple[str, ...]]], List[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], WSGIApplication]]) – Return type None
flask.api.index#flask.Flask.register_error_handler
flask.request To access incoming request data, you can use the global request object. Flask parses incoming request data for you and gives you access to it through that global object. Internally Flask makes sure that you always get the correct data for the active thread if you are in a multithreaded environment. This is a proxy. See Notes On Proxies for more information. The request object is an instance of a Request.
flask.api.index#flask.request
request_class alias of flask.wrappers.Request
flask.api.index#flask.Flask.request_class
request_context(environ) Create a RequestContext representing a WSGI environment. Use a with block to push the context, which will make request point at this request. See The Request Context. Typically you should not call this from your own code. A request context is automatically pushed by the wsgi_app() when handling a request. Use test_request_context() to create an environment and context instead of this method. Parameters environ (dict) – a WSGI environment Return type flask.ctx.RequestContext
flask.api.index#flask.Flask.request_context
flask.request_finished This signal is sent right before the response is sent to the client. It is passed the response to be sent named response. Example subscriber: def log_response(sender, response, **extra): sender.logger.debug('Request context is about to close down. ' 'Response: %s', response) from flask import request_finished request_finished.connect(log_response, app)
flask.api.index#flask.request_finished
flask.request_started This signal is sent when the request context is set up, before any request processing happens. Because the request context is already bound, the subscriber can access the request with the standard global proxies such as request. Example subscriber: def log_request(sender, **extra): sender.logger.debug('Request context is set up') from flask import request_started request_started.connect(log_request, app)
flask.api.index#flask.request_started
flask.request_tearing_down This signal is sent when the request is tearing down. This is always called, even if an exception is caused. Currently functions listening to this signal are called after the regular teardown handlers, but this is not something you can rely on. Example subscriber: def close_db_connection(sender, **extra): session.close() from flask import request_tearing_down request_tearing_down.connect(close_db_connection, app) As of Flask 0.9, this will also be passed an exc keyword argument that has a reference to the exception that caused the teardown if there was one.
flask.api.index#flask.request_tearing_down
response_class alias of flask.wrappers.Response
flask.api.index#flask.Flask.response_class
root_path Absolute path to the package on the filesystem. Used to look up resources contained in the package.
flask.api.index#flask.Flask.root_path
route(rule, **options) Decorate a view function to register it with the given URL rule and options. Calls add_url_rule(), which has more details about the implementation. @app.route("/") def index(): return "Hello, World!" See URL Route Registrations. The endpoint name for the route defaults to the name of the view function if the endpoint parameter isn’t passed. The methods parameter defaults to ["GET"]. HEAD and OPTIONS are added automatically. Parameters rule (str) – The URL rule string. options (Any) – Extra options passed to the Rule object. Return type Callable
flask.api.index#flask.Flask.route
run(host=None, port=None, debug=None, load_dotenv=True, **options) Runs the application on a local development server. Do not use run() in a production setting. It is not intended to meet security and performance requirements for a production server. Instead, see Deployment Options for WSGI server recommendations. If the debug flag is set the server will automatically reload for code changes and show a debugger in case an exception happened. If you want to run the application in debug mode, but disable the code execution on the interactive debugger, you can pass use_evalex=False as parameter. This will keep the debugger’s traceback screen active, but disable code execution. It is not recommended to use this function for development with automatic reloading as this is badly supported. Instead you should be using the flask command line script’s run support. Keep in Mind Flask will suppress any server error with a generic error page unless it is in debug mode. As such to enable just the interactive debugger without the code reloading, you have to invoke run() with debug=True and use_reloader=False. Setting use_debugger to True without being in debug mode won’t catch any exceptions because there won’t be any to catch. Parameters host (Optional[str]) – 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' or the host in the SERVER_NAME config variable if present. port (Optional[int]) – the port of the webserver. Defaults to 5000 or the port defined in the SERVER_NAME config variable if present. debug (Optional[bool]) – if given, enable or disable debug mode. See debug. load_dotenv (bool) – Load the nearest .env and .flaskenv files to set environment variables. Will also change the working directory to the directory containing the first file found. options (Any) – the options to be forwarded to the underlying Werkzeug server. See werkzeug.serving.run_simple() for more information. Return type None Changelog Changed in version 1.0: If installed, python-dotenv will be used to load environment variables from .env and .flaskenv files. If set, the FLASK_ENV and FLASK_DEBUG environment variables will override env and debug. Threaded mode is enabled by default. Changed in version 0.10: The default port is now picked from the SERVER_NAME variable.
flask.api.index#flask.Flask.run
secret_key If a secret key is set, cryptographic components can use this to sign cookies and other things. Set this to a complex random value when you want to use the secure cookie for instance. This attribute can also be configured from the config with the SECRET_KEY configuration key. Defaults to None.
flask.api.index#flask.Flask.secret_key
select_jinja_autoescape(filename) Returns True if autoescaping should be active for the given template name. If no template name is given, returns True. Changelog New in version 0.5. Parameters filename (str) – Return type bool
flask.api.index#flask.Flask.select_jinja_autoescape
send_file_max_age_default A timedelta or number of seconds which is used as the default max_age for send_file(). The default is None, which tells the browser to use conditional requests instead of a timed cache. Configured with the SEND_FILE_MAX_AGE_DEFAULT configuration key. Changed in version 2.0: Defaults to None instead of 12 hours.
flask.api.index#flask.Flask.send_file_max_age_default
send_static_file(filename) The view function used to serve files from static_folder. A route is automatically registered for this view at static_url_path if static_folder is set. Changelog New in version 0.5. Parameters filename (str) – Return type Response
flask.api.index#flask.Flask.send_static_file
session_cookie_name The secure cookie uses this for the name of the session cookie. This attribute can also be configured from the config with the SESSION_COOKIE_NAME configuration key. Defaults to 'session'
flask.api.index#flask.Flask.session_cookie_name
session_interface = <flask.sessions.SecureCookieSessionInterface object> the session interface to use. By default an instance of SecureCookieSessionInterface is used here. Changelog New in version 0.8.
flask.api.index#flask.Flask.session_interface
shell_context_processor(f) Registers a shell context processor function. Changelog New in version 0.11. Parameters f (Callable) – Return type Callable
flask.api.index#flask.Flask.shell_context_processor
shell_context_processors: t.List[t.Callable[], t.Dict[str, t.Any]]] A list of shell context processor functions that should be run when a shell context is created. Changelog New in version 0.11.
flask.api.index#flask.Flask.shell_context_processors
should_ignore_error(error) This is called to figure out if an error should be ignored or not as far as the teardown system is concerned. If this function returns True then the teardown handlers will not be passed the error. Changelog New in version 0.10. Parameters error (Optional[BaseException]) – Return type bool
flask.api.index#flask.Flask.should_ignore_error
signals.signals_available True if the signaling system is available. This is the case when blinker is installed.
flask.api.index#flask.signals.signals_available
teardown_appcontext(f) Registers a function to be called when the application context ends. These functions are typically also called when the request context is popped. Example: ctx = app.app_context() ctx.push() ... ctx.pop() When ctx.pop() is executed in the above example, the teardown functions are called just before the app context moves from the stack of active contexts. This becomes relevant if you are using such constructs in tests. Since a request context typically also manages an application context it would also be called when you pop a request context. When a teardown function was called because of an unhandled exception it will be passed an error object. If an errorhandler() is registered, it will handle the exception and the teardown will not receive it. The return values of teardown functions are ignored. Changelog New in version 0.9. Parameters f (Callable[[Optional[BaseException]], flask.wrappers.Response]) – Return type Callable[[Optional[BaseException]], flask.wrappers.Response]
flask.api.index#flask.Flask.teardown_appcontext
teardown_appcontext_funcs: t.List[TeardownCallable] A list of functions that are called when the application context is destroyed. Since the application context is also torn down if the request ends this is the place to store code that disconnects from databases. Changelog New in version 0.9.
flask.api.index#flask.Flask.teardown_appcontext_funcs
teardown_request(f) Register a function to be run at the end of each request, regardless of whether there was an exception or not. These functions are executed when the request context is popped, even if not an actual request was performed. Example: ctx = app.test_request_context() ctx.push() ... ctx.pop() When ctx.pop() is executed in the above example, the teardown functions are called just before the request context moves from the stack of active contexts. This becomes relevant if you are using such constructs in tests. Teardown functions must avoid raising exceptions, since they . If they 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 an exception it will be passed an error object. The return values of teardown functions are ignored. Debug Note In debug mode Flask will not tear down a request on an exception immediately. Instead it will keep it alive so that the interactive debugger can still access it. This behavior can be controlled by the PRESERVE_CONTEXT_ON_EXCEPTION configuration variable. Parameters f (Callable[[Optional[BaseException]], Response]) – Return type Callable[[Optional[BaseException]], Response]
flask.api.index#flask.Flask.teardown_request
teardown_request_funcs: t.Dict[AppOrBlueprintKey, t.List[TeardownCallable]] A data structure of functions to call at the end of each request even if an exception is raised, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests. To register a function, use the teardown_request() decorator. This data structure is internal. It should not be modified directly and its format may change at any time.
flask.api.index#flask.Flask.teardown_request_funcs
template_context_processors: t.Dict[AppOrBlueprintKey, t.List[TemplateContextProcessorCallable]] A data structure of functions to call to pass extra context values when rendering templates, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests. To register a function, use the context_processor() decorator. This data structure is internal. It should not be modified directly and its format may change at any time.
flask.api.index#flask.Flask.template_context_processors
template_filter(name=None) A decorator that is used to register custom template filter. You can specify a name for the filter, otherwise the function name will be used. Example: @app.template_filter() def reverse(s): return s[::-1] Parameters name (Optional[str]) – the optional name of the filter, otherwise the function name will be used. Return type Callable
flask.api.index#flask.Flask.template_filter
template_folder The path to the templates folder, relative to root_path, to add to the template loader. None if templates should not be added.
flask.api.index#flask.Flask.template_folder
template_global(name=None) A decorator that is used to register a custom template global function. You can specify a name for the global function, otherwise the function name will be used. Example: @app.template_global() def double(n): return 2 * n Changelog New in version 0.10. Parameters name (Optional[str]) – the optional name of the global function, otherwise the function name will be used. Return type Callable
flask.api.index#flask.Flask.template_global
flask.template_rendered This signal is sent when a template was successfully rendered. The signal is invoked with the instance of the template as template and the context as dictionary (named context). Example subscriber: def log_template_renders(sender, template, context, **extra): sender.logger.debug('Rendering template "%s" with context %s', template.name or 'string template', context) from flask import template_rendered template_rendered.connect(log_template_renders, app)
flask.api.index#flask.template_rendered
template_test(name=None) A decorator that is used to register custom template test. You can specify a name for the test, otherwise the function name will be used. Example: @app.template_test() def is_prime(n): if n == 2: return True for i in range(2, int(math.ceil(math.sqrt(n))) + 1): if n % i == 0: return False return True Changelog New in version 0.10. Parameters name (Optional[str]) – the optional name of the test, otherwise the function name will be used. Return type Callable
flask.api.index#flask.Flask.template_test
testing The testing flag. Set this to True to enable the test mode of Flask extensions (and in the future probably also Flask itself). For example this might activate test helpers that have an additional runtime cost which should not be enabled by default. If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the default it’s implicitly enabled. This attribute can also be configured from the config with the TESTING configuration key. Defaults to False.
flask.api.index#flask.Flask.testing
test_client(use_cookies=True, **kwargs) Creates a test client for this application. For information about unit testing head over to Testing Flask Applications. Note that if you are testing for assertions or exceptions in your application code, you must set app.testing = True in order for the exceptions to propagate to the test client. Otherwise, the exception will be handled by the application (not visible to the test client) and the only indication of an AssertionError or other exception will be a 500 status code response to the test client. See the testing attribute. For example: app.testing = True client = app.test_client() The test client can be used in a with block to defer the closing down of the context until the end of the with block. This is useful if you want to access the context locals for testing: with app.test_client() as c: rv = c.get('/?vodka=42') assert request.args['vodka'] == '42' Additionally, you may pass optional keyword arguments that will then be passed to the application’s test_client_class constructor. For example: from flask.testing import FlaskClient class CustomClient(FlaskClient): def __init__(self, *args, **kwargs): self._authentication = kwargs.pop("authentication") super(CustomClient,self).__init__( *args, **kwargs) app.test_client_class = CustomClient client = app.test_client(authentication='Basic ....') See FlaskClient for more information. Changelog Changed in version 0.11: Added **kwargs to support passing additional keyword arguments to the constructor of test_client_class. New in version 0.7: The use_cookies parameter was added as well as the ability to override the client to be used by setting the test_client_class attribute. Changed in version 0.4: added support for with block usage for the client. Parameters use_cookies (bool) – kwargs (Any) – Return type FlaskClient
flask.api.index#flask.Flask.test_client
test_client_class: Optional[Type[FlaskClient]] = None the test client that is used with when test_client is used. Changelog New in version 0.7.
flask.api.index#flask.Flask.test_client_class
test_cli_runner(**kwargs) Create a CLI runner for testing CLI commands. See Testing CLI Commands. Returns an instance of test_cli_runner_class, by default FlaskCliRunner. The Flask app object is passed as the first argument. Changelog New in version 1.0. Parameters kwargs (Any) – Return type FlaskCliRunner
flask.api.index#flask.Flask.test_cli_runner
test_cli_runner_class: Optional[Type[FlaskCliRunner]] = None The CliRunner subclass, by default FlaskCliRunner that is used by test_cli_runner(). Its __init__ method should take a Flask app object as the first argument. Changelog New in version 1.0.
flask.api.index#flask.Flask.test_cli_runner_class
test_request_context(*args, **kwargs) Create a RequestContext for a WSGI environment created from the given values. This is mostly useful during testing, where you may want to run a function that uses request data without dispatching a full request. See The Request Context. Use a with block to push the context, which will make request point at the request for the created environment. with test_request_context(...): generate_report() When using the shell, it may be easier to push and pop the context manually to avoid indentation. ctx = app.test_request_context(...) ctx.push() ... ctx.pop() Takes the same arguments as Werkzeug’s EnvironBuilder, with some defaults from the application. See the linked Werkzeug docs for most of the available arguments. Flask-specific behavior is listed here. Parameters path – URL path being requested. base_url – Base URL where the app is being served, which path is relative to. If not given, built from PREFERRED_URL_SCHEME, subdomain, SERVER_NAME, and APPLICATION_ROOT. subdomain – Subdomain name to append to SERVER_NAME. url_scheme – Scheme to use instead of PREFERRED_URL_SCHEME. data – The request body, either as a string or a dict of form keys and values. json – If given, this is serialized as JSON and passed as data. Also defaults content_type to application/json. args (Any) – other positional arguments passed to EnvironBuilder. kwargs (Any) – other keyword arguments passed to EnvironBuilder. Return type flask.ctx.RequestContext
flask.api.index#flask.Flask.test_request_context
trap_http_exception(e) Checks if an HTTP exception should be trapped or not. By default this will return False for all exceptions except for a bad request key error if TRAP_BAD_REQUEST_ERRORS is set to True. It also returns True if TRAP_HTTP_EXCEPTIONS is set to True. This is called for all HTTP exceptions raised by a view function. If it returns True for any exception the error handler for this exception is not called and it shows up as regular exception in the traceback. This is helpful for debugging implicitly raised HTTP exceptions. Changelog Changed in version 1.0: Bad request errors are not trapped by default in debug mode. New in version 0.8. Parameters e (Exception) – Return type bool
flask.api.index#flask.Flask.trap_http_exception
update_template_context(context) Update the template context with some commonly used variables. This injects request, session, config and g into the template context as well as everything template context processors want to inject. Note that the as of Flask 0.6, the original values in the context will not be overridden if a context processor decides to return a value with the same key. Parameters context (dict) – the context as a dictionary that is updated in place to add extra variables. Return type None
flask.api.index#flask.Flask.update_template_context
url_build_error_handlers: t.List[t.Callable[[Exception, str, dict], str]] A list of functions that are called when url_for() raises a BuildError. Each function registered here is called with error, endpoint and values. If a function returns None or raises a BuildError the next function is tried. Changelog New in version 0.9.
flask.api.index#flask.Flask.url_build_error_handlers
url_defaults(f) Callback function for URL defaults for all view functions of the application. It’s called with the endpoint and values and should update the values passed in place. Parameters f (Callable[[str, dict], None]) – Return type Callable[[str, dict], None]
flask.api.index#flask.Flask.url_defaults
url_default_functions: t.Dict[AppOrBlueprintKey, t.List[URLDefaultCallable]] A data structure of functions to call to modify the keyword arguments when generating URLs, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests. To register a function, use the url_defaults() decorator. This data structure is internal. It should not be modified directly and its format may change at any time.
flask.api.index#flask.Flask.url_default_functions
url_map The Map for this instance. You can use this to change the routing converters after the class was created but before any routes are connected. Example: from werkzeug.routing import BaseConverter class ListConverter(BaseConverter): def to_python(self, value): return value.split(',') def to_url(self, values): return ','.join(super(ListConverter, self).to_url(value) for value in values) app = Flask(__name__) app.url_map.converters['list'] = ListConverter
flask.api.index#flask.Flask.url_map
url_map_class alias of werkzeug.routing.Map
flask.api.index#flask.Flask.url_map_class
url_rule_class alias of werkzeug.routing.Rule
flask.api.index#flask.Flask.url_rule_class
url_value_preprocessor(f) Register a URL value preprocessor function for all view functions in the application. These functions will be called before the before_request() functions. The function can modify the values captured from the matched url before they are passed to the view. For example, this can be used to pop a common language code value and place it in g rather than pass it to every view. The function is passed the endpoint name and values dict. The return value is ignored. Parameters f (Callable[[Optional[str], Optional[dict]], None]) – Return type Callable[[Optional[str], Optional[dict]], None]
flask.api.index#flask.Flask.url_value_preprocessor
url_value_preprocessors: t.Dict[AppOrBlueprintKey, t.List[URLValuePreprocessorCallable]] A data structure of functions to call to modify the keyword arguments passed to the view function, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests. To register a function, use the url_value_preprocessor() decorator. This data structure is internal. It should not be modified directly and its format may change at any time.
flask.api.index#flask.Flask.url_value_preprocessors
use_x_sendfile Enable this if you want to use the X-Sendfile feature. Keep in mind that the server has to support this. This only affects files sent with the send_file() method. Changelog New in version 0.2. This attribute can also be configured from the config with the USE_X_SENDFILE configuration key. Defaults to False.
flask.api.index#flask.Flask.use_x_sendfile
view_functions: t.Dict[str, t.Callable] A dictionary mapping endpoint names to view functions. To register a view function, use the route() decorator. This data structure is internal. It should not be modified directly and its format may change at any time.
flask.api.index#flask.Flask.view_functions
wsgi_app(environ, start_response) The actual WSGI application. This is not implemented in __call__() so that middlewares can be applied without losing a reference to the app object. 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. Changelog Changed in version 0.7: Teardown events for the request and app contexts are called even if an unhandled error occurs. Other events may not be called depending on when an error occurs during dispatch. See Callbacks and Errors. Parameters environ (dict) – A WSGI environment. start_response (Callable) – A callable accepting a status code, a list of headers, and an optional exception context to start the response. Return type Any
flask.api.index#flask.Flask.wsgi_app
flask._app_ctx_stack The internal LocalStack that holds AppContext instances. Typically, the current_app and g proxies should be accessed instead of the stack. Extensions can access the contexts on the stack as a namespace to store data. Changelog New in version 0.9.
flask.api.index#flask._app_ctx_stack
flask._request_ctx_stack The internal LocalStack that holds RequestContext instances. Typically, the request and session proxies should be accessed instead of the stack. It may be useful to access the stack in extension code. The following attributes are always present on each layer of the stack: app the active Flask application. url_adapter the URL adapter that was used to match the request. request the current request object. session the active session object. g an object with all the attributes of the flask.g object. flashes an internal cache for the flashed messages. Example usage: from flask import _request_ctx_stack def get_session(): ctx = _request_ctx_stack.top if ctx is not None: return ctx.session
flask.api.index#flask._request_ctx_stack
class flask.testing.FlaskClient(*args, **kwargs) Works like a regular Werkzeug test client but has some knowledge about how Flask works to defer the cleanup of the request context stack to the end of a with body when used in a with statement. For general information about how to use this class refer to werkzeug.test.Client. Changelog Changed in version 0.12: app.test_client() includes preset default environment, which can be set after instantiation of the app.test_client() object in client.environ_base. Basic usage is outlined in the Testing Flask Applications chapter. Parameters args (Any) – kwargs (Any) – Return type None open(*args, as_tuple=False, buffered=False, follow_redirects=False, **kwargs) Generate an environ dict from the given arguments, make a request to the application using it, and return the response. Parameters args (Any) – Passed to EnvironBuilder to create the environ for the request. If a single arg is passed, it can be an existing EnvironBuilder or an environ dict. buffered (bool) – Convert the iterator returned by the app into a list. If the iterator has a close() method, it is called automatically. follow_redirects (bool) – Make additional requests to follow HTTP redirects until a non-redirect status is returned. TestResponse.history lists the intermediate responses. as_tuple (bool) – kwargs (Any) – Return type Response Changed in version 2.0: as_tuple is deprecated and will be removed in Werkzeug 2.1. Use TestResponse.request and request.environ instead. Changed in version 2.0: The request input stream is closed when calling response.close(). Input streams for redirects are automatically closed. Changelog Changed in version 0.5: If a dict is provided as file in the dict for the data parameter the content type has to be called content_type instead of mimetype. This change was made for consistency with werkzeug.FileWrapper. Changed in version 0.5: Added the follow_redirects parameter. session_transaction(*args, **kwargs) When used in combination with a with statement this opens a session transaction. This can be used to modify the session that the test client uses. Once the with block is left the session is stored back. with client.session_transaction() as session: session['value'] = 42 Internally this is implemented by going through a temporary test request context and since session handling could depend on request variables this function accepts the same arguments as test_request_context() which are directly passed through. Parameters args (Any) – kwargs (Any) – Return type Generator[flask.sessions.SessionMixin, None, None]
flask.api.index#flask.testing.FlaskClient
open(*args, as_tuple=False, buffered=False, follow_redirects=False, **kwargs) Generate an environ dict from the given arguments, make a request to the application using it, and return the response. Parameters args (Any) – Passed to EnvironBuilder to create the environ for the request. If a single arg is passed, it can be an existing EnvironBuilder or an environ dict. buffered (bool) – Convert the iterator returned by the app into a list. If the iterator has a close() method, it is called automatically. follow_redirects (bool) – Make additional requests to follow HTTP redirects until a non-redirect status is returned. TestResponse.history lists the intermediate responses. as_tuple (bool) – kwargs (Any) – Return type Response Changed in version 2.0: as_tuple is deprecated and will be removed in Werkzeug 2.1. Use TestResponse.request and request.environ instead. Changed in version 2.0: The request input stream is closed when calling response.close(). Input streams for redirects are automatically closed. Changelog Changed in version 0.5: If a dict is provided as file in the dict for the data parameter the content type has to be called content_type instead of mimetype. This change was made for consistency with werkzeug.FileWrapper. Changed in version 0.5: Added the follow_redirects parameter.
flask.api.index#flask.testing.FlaskClient.open
session_transaction(*args, **kwargs) When used in combination with a with statement this opens a session transaction. This can be used to modify the session that the test client uses. Once the with block is left the session is stored back. with client.session_transaction() as session: session['value'] = 42 Internally this is implemented by going through a temporary test request context and since session handling could depend on request variables this function accepts the same arguments as test_request_context() which are directly passed through. Parameters args (Any) – kwargs (Any) – Return type Generator[flask.sessions.SessionMixin, None, None]
flask.api.index#flask.testing.FlaskClient.session_transaction
class flask.testing.FlaskCliRunner(app, **kwargs) A CliRunner for testing a Flask app’s CLI commands. Typically created using test_cli_runner(). See Testing CLI Commands. Parameters app (Flask) – kwargs (Any) – Return type None invoke(cli=None, args=None, **kwargs) Invokes a CLI command in an isolated environment. See CliRunner.invoke for full method documentation. See Testing CLI Commands for examples. If the obj argument is not given, passes an instance of ScriptInfo that knows how to load the Flask app being tested. Parameters cli (Optional[Any]) – Command object to invoke. Default is the app’s cli group. args (Optional[Any]) – List of strings to invoke the command with. kwargs (Any) – Returns a Result object. Return type Any
flask.api.index#flask.testing.FlaskCliRunner
invoke(cli=None, args=None, **kwargs) Invokes a CLI command in an isolated environment. See CliRunner.invoke for full method documentation. See Testing CLI Commands for examples. If the obj argument is not given, passes an instance of ScriptInfo that knows how to load the Flask app being tested. Parameters cli (Optional[Any]) – Command object to invoke. Default is the app’s cli group. args (Optional[Any]) – List of strings to invoke the command with. kwargs (Any) – Returns a Result object. Return type Any
flask.api.index#flask.testing.FlaskCliRunner.invoke
class flask.cli.FlaskGroup(add_default_commands=True, create_app=None, add_version_option=True, load_dotenv=True, set_debug_flag=True, **extra) Special subclass of the AppGroup group 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. see Custom Scripts. Parameters add_default_commands – if this is True then the default run and shell commands will be added. add_version_option – adds the --version option. create_app – an optional callback that is passed the script info and returns the loaded app. load_dotenv – Load the nearest .env and .flaskenv files to set environment variables. Will also change the working directory to the directory containing the first file found. set_debug_flag – Set the app’s debug flag based on the active environment Changelog Changed in version 1.0: If installed, python-dotenv will be used to load environment variables from .env and .flaskenv files. get_command(ctx, name) Given a context and a command name, this returns a Command object if it exists or returns None. list_commands(ctx) Returns a list of subcommand names in the order they should appear. main(*args, **kwargs) This is the way to invoke a script with all the bells and whistles as a command line application. This will always terminate the application after a call. If this is not wanted, SystemExit needs to be caught. This method is also available by directly calling the instance of a Command. Parameters args – the arguments that should be used for parsing. If not provided, sys.argv[1:] is used. prog_name – the program name that should be used. By default the program name is constructed by taking the file name from sys.argv[0]. complete_var – the environment variable that controls the bash completion support. The default is "_<prog_name>_COMPLETE" with prog_name in uppercase. standalone_mode – the default behavior is to invoke the script in standalone mode. Click will then handle exceptions and convert them into error messages and the function will never return but shut down the interpreter. If this is set to False they will be propagated to the caller and the return value of this function is the return value of invoke(). extra – extra keyword arguments are forwarded to the context constructor. See Context for more information. Changed in version 8.0: When taking arguments from sys.argv on Windows, glob patterns, user dir, and env vars are expanded. Changed in version 3.0: Added the standalone_mode parameter.
flask.api.index#flask.cli.FlaskGroup
get_command(ctx, name) Given a context and a command name, this returns a Command object if it exists or returns None.
flask.api.index#flask.cli.FlaskGroup.get_command
list_commands(ctx) Returns a list of subcommand names in the order they should appear.
flask.api.index#flask.cli.FlaskGroup.list_commands
main(*args, **kwargs) This is the way to invoke a script with all the bells and whistles as a command line application. This will always terminate the application after a call. If this is not wanted, SystemExit needs to be caught. This method is also available by directly calling the instance of a Command. Parameters args – the arguments that should be used for parsing. If not provided, sys.argv[1:] is used. prog_name – the program name that should be used. By default the program name is constructed by taking the file name from sys.argv[0]. complete_var – the environment variable that controls the bash completion support. The default is "_<prog_name>_COMPLETE" with prog_name in uppercase. standalone_mode – the default behavior is to invoke the script in standalone mode. Click will then handle exceptions and convert them into error messages and the function will never return but shut down the interpreter. If this is set to False they will be propagated to the caller and the return value of this function is the return value of invoke(). extra – extra keyword arguments are forwarded to the context constructor. See Context for more information. Changed in version 8.0: When taking arguments from sys.argv on Windows, glob patterns, user dir, and env vars are expanded. Changed in version 3.0: Added the standalone_mode parameter.
flask.api.index#flask.cli.FlaskGroup.main