App configuration¶
-
class
coaster.app.KeyRotationWrapper(cls, secret_keys, **kwargs)[source]¶ Wrapper to support multiple secret keys in itsdangerous.
The first secret key is used for all operations, but if it causes a BadSignature exception, the other secret keys are tried in order.
Parameters: - cls – Signing class from itsdangerous (eg: URLSafeTimedSerializer)
- secret_keys – List of secret keys
- kwargs – Arguments to pass to each signer/serializer
-
class
coaster.app.RotatingKeySecureCookieSessionInterface[source]¶ Replaces the serializer with key rotation support
-
class
coaster.app.Flask(import_name: str, static_url_path: Optional[str] = None, static_folder: Optional[str] = 'static', static_host: Optional[str] = None, host_matching: bool = False, subdomain_matching: bool = False, template_folder: Optional[str] = 'templates', instance_path: Optional[str] = None, instance_relative_config: bool = False, root_path: Optional[str] = None)[source]¶ The flask object implements a WSGI application and acts as the central object. It is passed the name of the module or package of the application. Once it is created it will act as a central registry for the view functions, the URL rules, template configuration and much more.
The name of the package is used to resolve resources from inside the package or the folder the module is contained in depending on if the package parameter resolves to an actual python package (a folder with an
__init__.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.
New in version 1.0: The
host_matchingandstatic_hostparameters were added.New in version 1.0: The
subdomain_matchingparameter was added. Subdomain matching needs to be enabled manually now. SettingSERVER_NAMEdoes not implicitly enable it.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 is served at
static_url_path. Relative to the applicationroot_pathor an absolute path. Defaults to'static'. - static_host – the host to use when adding the static route.
Defaults to None. Required when using
host_matching=Truewith astatic_folderconfigured. - host_matching – set
url_map.host_matchingattribute. Defaults to False. - subdomain_matching – consider the subdomain relative to
SERVER_NAMEwhen matching routes. Defaults to False. - 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 – The path to the root of the application files. This should only be set manually when it can’t be detected automatically, such as for namespace packages.
-
add_template_filter(f: Callable[[Any], str], name: Optional[str] = None) → 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: Callable[[], Any], name: Optional[str] = None) → 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: Callable[[Any], bool], name: Optional[str] = None) → 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: str, endpoint: Optional[str] = None, view_func: Optional[Callable] = None, provide_automatic_options: Optional[bool] = None, **options) → None[source]¶ Register a rule for routing incoming requests and building URLs. The
route()decorator is a shortcut to call this with theview_funcargument. These are equivalent:@app.route("/") def index(): ...
def index(): ... app.add_url_rule("/", view_func=index)
The endpoint name for the route defaults to the name of the view function if the
endpointparameter isn’t passed. An error will be raised if a function has already been registered for the endpoint.The
methodsparameter defaults to["GET"].HEADis always added automatically, andOPTIONSis added automatically by default.view_funcdoes not necessarily need to be passed, but if the rule should participate in routing an endpoint name must be associated with a view function at some point with theendpoint()decorator.app.add_url_rule("/", endpoint="index") @app.endpoint("index") def index(): ...
If
view_funchas arequired_methodsattribute, those methods are added to the passed and automatic methods. If it has aprovide_automatic_methodsattribute, it is used as the default if the parameter is not passed.Parameters: - rule – The URL rule string.
- endpoint – The endpoint name to associate with the rule
and view function. Used when routing and building URLs.
Defaults to
view_func.__name__. - view_func – The view function to associate with the endpoint name.
- provide_automatic_options – Add the
OPTIONSmethod and respond toOPTIONSrequests automatically. - options – Extra options passed to the
Ruleobject.
-
app_context() → flask.ctx.AppContext[source]¶ Create an
AppContext. Use as awithblock to push the context, which will makecurrent_apppoint at this application.An application context is automatically pushed by
RequestContext.push()when handling a request, and when running a CLI command. Use this to manually create a context outside of these situations.with app.app_context(): init_db()
See /appcontext.
New in version 0.9.
-
app_ctx_globals_class¶ alias of
flask.ctx._AppCtxGlobals
-
async_to_sync(func: Callable[[...], Coroutine[T_co, T_contra, V_co]]) → Callable[[...], Any][source]¶ Return a sync function that will run the coroutine function.
result = app.async_to_sync(func)(*args, **kwargs)
Override this method to change how the app converts async code to be synchronously callable.
New in version 2.0.
-
auto_find_instance_path() → str[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: Callable[[], None]) → Callable[[], None][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 list of functions that will be called at the beginning of the first request to this instance. To register a function, use the
before_first_request()decorator.New in version 0.8.
-
blueprints= None¶ Maps registered blueprint names to blueprint objects. The dict retains the order the blueprints were registered in. Blueprints can be registered multiple times, this dict does not track how often they were attached.
New in version 0.7.
-
config= None¶ The configuration dictionary as
Config. This behaves exactly like a regular dictionary but supports additional methods to load a config from files.
-
config_class¶ alias of
flask.config.Config
-
create_global_jinja_loader() → flask.templating.DispatchingJinjaLoader[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() → flask.templating.Environment[source]¶ Create the Jinja environment based on
jinja_optionsand the various Jinja-related methods of the app. Changingjinja_optionsafter this will have no effect. Also adds Flask-related globals and filters to the environment.Changed in version 0.11:
Environment.auto_reloadset in accordance withTEMPLATES_AUTO_RELOADconfiguration option.New in version 0.5.
-
create_url_adapter(request: Optional[flask.wrappers.Request]) → Optional[werkzeug.routing.MapAdapter][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.
Changed in version 1.0:
SERVER_NAMEno longer implicitly enables subdomain matching. Usesubdomain_matchinginstead.
-
debug¶ Whether debug mode is enabled. When using
flask runto start the development server, an interactive debugger will be shown for unhandled exceptions, and the server will be reloaded when code changes. This maps to theDEBUGconfig key. This is enabled whenenvis'development'and is overridden by theFLASK_DEBUGenvironment variable. It may not behave as expected if set in code.Do not enable debug mode when deploying in production.
Default:
Trueifenvis'development', orFalseotherwise.
-
default_config= {'APPLICATION_ROOT': '/', 'DEBUG': None, 'ENV': None, 'EXPLAIN_TEMPLATE_LOADING': False, 'JSONIFY_MIMETYPE': 'application/json', 'JSONIFY_PRETTYPRINT_REGULAR': False, 'JSON_AS_ASCII': True, 'JSON_SORT_KEYS': True, 'MAX_CONTENT_LENGTH': None, 'MAX_COOKIE_SIZE': 4093, 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(days=31), 'PREFERRED_URL_SCHEME': 'http', 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'PROPAGATE_EXCEPTIONS': None, 'SECRET_KEY': None, 'SEND_FILE_MAX_AGE_DEFAULT': None, 'SERVER_NAME': None, 'SESSION_COOKIE_DOMAIN': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_SAMESITE': None, 'SESSION_COOKIE_SECURE': False, 'SESSION_REFRESH_EACH_REQUEST': True, 'TEMPLATES_AUTO_RELOAD': None, 'TESTING': False, 'TRAP_BAD_REQUEST_ERRORS': None, 'TRAP_HTTP_EXCEPTIONS': False, 'USE_X_SENDFILE': False}¶ Default configuration parameters.
-
dispatch_request() → 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][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: Optional[BaseException] = <object object>) → None[source]¶ Called right before the application context is popped.
When handling a request, the application context is popped after the request context. See
do_teardown_request().This calls all functions decorated with
teardown_appcontext(). Then theappcontext_tearing_downsignal is sent.This is called by
AppContext.pop().New in version 0.9.
-
do_teardown_request(exc: Optional[BaseException] = <object object>) → None[source]¶ 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(), andBlueprint.teardown_request()if a blueprint handled the request. Finally, therequest_tearing_downsignal is sent.This is called by
RequestContext.pop(), which may be delayed during testing to maintain access to resources.Parameters: exc – An unhandled exception raised while dispatching the request. Detected from the current exception information if not passed. Passed to each teardown function. Changed in version 0.9: Added the
excargument.
-
ensure_sync(func: Callable) → Callable[source]¶ Ensure that the function is synchronous for WSGI workers. Plain
deffunctions are returned as-is.async deffunctions 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.
-
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
ENVconfig key. This is set by theFLASK_ENVenvironment variable and may not behave as expected if set in code.Do not enable development when deploying in production.
Default:
'production'
-
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.
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.
-
finalize_request(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, werkzeug.exceptions.HTTPException], from_error_handler: bool = False) → flask.wrappers.Response[source]¶ Given the return value from a view function this finalizes the request by converting it into a response and invoking the postprocessing functions. This is invoked for both normal request dispatching as well as error handlers.
Because this means that it might be called as a result of a failure a special safe mode is available which can be enabled with the from_error_handler flag. If enabled, failures in response processing will be logged and otherwise ignored.
Internal:
-
full_dispatch_request() → flask.wrappers.Response[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: Exception) → flask.wrappers.Response[source]¶ 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_exceptionsignal.If
propagate_exceptionsisTrue, 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 anInternalServerErroris returned.If an error handler is registered for
InternalServerErroror500, it will be used. For consistency, the handler will always receive theInternalServerError. The original unhandled exception is available ase.original_exception.Changed in version 1.1.0: Always passes the
InternalServerErrorinstance to the handler, settingoriginal_exceptionto the unhandled error.Changed in version 1.1.0:
after_requestfunctions and other finalization is done even for the default 500 response when there is no handler.New in version 0.3.
-
handle_http_exception(e: werkzeug.exceptions.HTTPException) → 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][source]¶ Handles an HTTP exception. By default this will invoke the registered error handlers and fall back to returning the exception as response.
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
HTTPExcpetionsubclasses can be handled with a catch-all handler for the baseHTTPException.New in version 0.3.
-
handle_url_build_error(error: Exception, endpoint: str, values: dict) → str[source]¶ Handle
BuildErroronurl_for().
-
handle_user_exception(e: Exception) → 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][source]¶ This method is called whenever an exception occurs that should be handled. A special case is
HTTPExceptionwhich is forwarded to thehandle_http_exception()method. This function will either return a response value or reraise the exception with the same traceback.Changed in version 1.0: Key errors raised from request data like
formshow the bad key in debug mode rather than a generic bad request message.New in version 0.7.
-
inject_url_defaults(endpoint: str, values: dict) → None[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() → ValuesView[Blueprint][source]¶ Iterates over all blueprints by the order they were registered.
New in version 0.11.
-
jinja_env[source]¶ The Jinja environment used to load templates.
The environment is created the first time this property is accessed. Changing
jinja_optionsafter that will have no effect.
-
jinja_environment¶ alias of
flask.templating.Environment
-
jinja_options= {}¶ Options that are passed to the Jinja environment in
create_jinja_environment(). Changing these options after the environment is created (accessingjinja_env) will have no effect.Changed in version 1.1.0: This is a
dictinstead of anImmutableDictto allow easier configuration.
-
json_decoder¶ alias of
flask.json.JSONDecoder
-
json_encoder¶ alias of
flask.json.JSONEncoder
-
log_exception(exc_info: Union[Tuple[type, BaseException, traceback], Tuple[None, None, None]]) → None[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[source]¶ A standard Python
Loggerfor the app, with the same name asname.In debug mode, the logger’s
levelwill be set toDEBUG.If there are no handlers configured, a default handler will be added. See /logging for more information.
Changed in version 1.1.0: The logger takes the same name as
namerather than hard-coding"flask.app".Changed in version 1.0.0: Behavior was simplified. The logger is always named
"flask.app". The level is only set during configuration, it doesn’t checkapp.debugeach time. Only one format is used, not different ones depending onapp.debug. No handlers are removed, and a handler is only added if no handlers are already configured.New in version 0.3.
-
make_config(instance_relative: bool = False) → flask.config.Config[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() → flask.wrappers.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_response(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]) → flask.wrappers.Response[source]¶ Convert the return value from a view function to an instance of
response_class.Parameters: rv – 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 forview_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), wherebodyis any of the other types allowed here,statusis a string or an integer, andheadersis a dictionary or a list of(key, value)tuples. Ifbodyis aresponse_classinstance,statusoverwrites the exiting value andheadersare extended. response_class- The object is returned unchanged.
- other
Responseclass - 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.
Changed in version 0.9: Previously a tuple was interpreted as the arguments for the response object.
-
make_shell_context() → dict[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: str, mode: str = 'rb') → IO[AnyStr][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’.
-
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() → 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, None][source]¶ Called before the request is dispatched. Calls
url_value_preprocessorsregistered with the app and the current blueprint (if any). Then callsbefore_request_funcsregistered 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.
-
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: flask.wrappers.Response) → flask.wrappers.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: flask.wrappers.Request) → te.NoReturn[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: Blueprint, **options) → None[source]¶ Register a
Blueprinton 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’sblueprints.Parameters: - 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 – Additional keyword arguments are passed to
BlueprintSetupState. They can be accessed inrecord()callbacks.
Changed in version 2.0.1: The
nameoption can be used to change the (pre-dotted) name the blueprint is registered with. This allows the same blueprint to be registered multiple times with unique names forurl_for.New in version 0.7.
-
request_class¶ alias of
flask.wrappers.Request
-
request_context(environ: dict) → flask.ctx.RequestContext[source]¶ Create a
RequestContextrepresenting a WSGI environment. Use awithblock to push the context, which will makerequestpoint at this request.See /reqcontext.
Typically you should not call this from your own code. A request context is automatically pushed by the
wsgi_app()when handling a request. Usetest_request_context()to create an environment and context instead of this method.Parameters: environ – a WSGI environment
-
response_class¶ alias of
flask.wrappers.Response
-
run(host: Optional[str] = None, port: Optional[int] = None, debug: Optional[bool] = None, load_dotenv: bool = True, **options) → None[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 /deploying/index 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.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'or the host in theSERVER_NAMEconfig variable if present. - 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. - load_dotenv – Load the nearest
.envand.flaskenvfiles to set environment variables. Will also change the working directory to the directory containing the first file found. - options – the options to be forwarded to the underlying Werkzeug
server. See
werkzeug.serving.run_simple()for more information.
Changed in version 1.0: If installed, python-dotenv will be used to load environment variables from
.envand.flaskenvfiles.If set, the
FLASK_ENVandFLASK_DEBUGenvironment variables will overrideenvanddebug.Threaded mode is enabled by default.
Changed in version 0.10: The default port is now picked from the
SERVER_NAMEvariable.- host – the hostname to listen on. Set this to
-
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: str) → bool[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
timedeltaor number of seconds which is used as the defaultmax_ageforsend_file(). The default isNone, which tells the browser to use conditional requests instead of a timed cache.Configured with the
SEND_FILE_MAX_AGE_DEFAULTconfiguration key.Changed in version 2.0: Defaults to
Noneinstead of 12 hours.
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>¶ the session interface to use. By default an instance of
SecureCookieSessionInterfaceis used here.New in version 0.8.
-
shell_context_processor(f: Callable) → Callable[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: Optional[BaseException]) → bool[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: Callable[[Optional[BaseException]], Response]) → Callable[[Optional[BaseException]], flask.wrappers.Response][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 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.
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.
-
template_filter(name: Optional[str] = None) → Callable[[Callable[[Any], str]], Callable[[Any], str]][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: Optional[str] = None) → Callable[[Callable[[], Any]], Callable[[], Any]][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: Optional[str] = None) → Callable[[Callable[[Any], bool]], Callable[[Any], bool]][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.
-
templates_auto_reload¶ Reload templates when they are changed. Used by
create_jinja_environment().This attribute can be configured with
TEMPLATES_AUTO_RELOAD. If not set, it will be enabled in debug mode.New in version 1.0: This property was added but the underlying config and behavior already existed.
-
test_cli_runner(**kwargs) → FlaskCliRunner[source]¶ Create a CLI runner for testing CLI commands. See Testing CLI Commands.
Returns an instance of
test_cli_runner_class, by defaultFlaskCliRunner. The Flask app object is passed as the first argument.New in version 1.0.
-
test_cli_runner_class= None¶ The
CliRunnersubclass, by defaultFlaskCliRunnerthat is used bytest_cli_runner(). Its__init__method should take a Flask app object as the first argument.New in version 1.0.
-
test_client(use_cookies: bool = True, **kwargs) → FlaskClient[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, *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
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) → flask.ctx.RequestContext[source]¶ Create a
RequestContextfor 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 /reqcontext.
Use a
withblock to push the context, which will makerequestpoint 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
pathis relative to. If not given, built fromPREFERRED_URL_SCHEME,subdomain,SERVER_NAME, andAPPLICATION_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 defaultscontent_typetoapplication/json. - args – other positional arguments passed to
EnvironBuilder. - kwargs – other keyword arguments passed to
EnvironBuilder.
-
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 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
TESTINGconfiguration key. Defaults toFalse.
-
trap_http_exception(e: Exception) → bool[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.Changed in version 1.0: Bad request errors are not trapped by default in debug mode.
New in version 0.8.
-
try_trigger_before_first_request_functions() → None[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: dict) → None[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_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(super(ListConverter, self).to_url(value) for value in values) app = Flask(__name__) app.url_map.converters['list'] = ListConverter
-
url_map_class¶ alias of
werkzeug.routing.Map
-
url_rule_class¶ alias of
werkzeug.routing.Rule
-
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.
-
wsgi_app(environ: dict, start_response: Callable) → Any[source]¶ 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.
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 – A WSGI environment.
- start_response – A callable accepting a status code, a list of headers, and an optional exception context to start the response.
-
coaster.app.init_app(app, init_logging=True)[source]¶ Configure an app depending on the environment. Loads settings from a file named
settings.pyin the instance folder, followed by additional settings from one ofdevelopment.py,production.pyortesting.py. Typical usage:from flask import Flask import coaster.app app = Flask(__name__, instance_relative_config=True) coaster.app.init_app(app) # Guess environment automatically
init_app()also configures logging by callingcoaster.logger.init_app().Parameters: - app – App to be configured
- init_logging (bool) – Call coaster.logger.init_app (default True)