doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
before_app_first_request(f) Like Flask.before_first_request(). Such a function is executed before the first request to the application. Parameters f (Callable[[], None]) – Return type Callable[[], None]
flask.api.index#flask.Blueprint.before_app_first_request
before_app_request(f) Like Flask.before_request(). Such a function is executed before each request, even if outside of a blueprint. Parameters f (Callable[[], None]) – Return type Callable[[], None]
flask.api.index#flask.Blueprint.before_app_request
before_request(f) Register a function to run before each request. For example, this can be used to open a database connection, or to load the logged in user from the session. @app.before_request def load_user(): if "user_id" in session: g.user = db.session.get(session["user_id"]) The function will be called without any arguments. If it 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. Parameters f (Callable[[], None]) – Return type Callable[[], None]
flask.api.index#flask.Blueprint.before_request
before_request_funcs: t.Dict[AppOrBlueprintKey, t.List[BeforeRequestCallable]] A data structure of functions to call at the beginning of each request, 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 before_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.Blueprint.before_request_funcs
cli The Click command group for registering CLI commands for this object. The commands are available from the flask command once the application has been discovered and blueprints have been registered.
flask.api.index#flask.Blueprint.cli
context_processor(f) Registers a template context processor function. Parameters f (Callable[[], Dict[str, Any]]) – Return type Callable[[], Dict[str, Any]]
flask.api.index#flask.Blueprint.context_processor
delete(rule, **options) Shortcut for route() with methods=["DELETE"]. New in version 2.0. Parameters rule (str) – options (Any) – Return type Callable
flask.api.index#flask.Blueprint.delete
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.Blueprint.endpoint
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.Blueprint.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.Blueprint.error_handler_spec
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.Blueprint.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.Blueprint.get_send_file_max_age
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.Blueprint.import_name
json_decoder: Optional[Type[json.decoder.JSONDecoder]] = None Blueprint local JSON decoder class to use. Set to None to use the app’s json_decoder.
flask.api.index#flask.Blueprint.json_decoder
json_encoder: Optional[Type[json.encoder.JSONEncoder]] = None Blueprint local JSON encoder class to use. Set to None to use the app’s json_encoder.
flask.api.index#flask.Blueprint.json_encoder
make_setup_state(app, options, first_registration=False) Creates an instance of BlueprintSetupState() object that is later passed to the register callback functions. Subclasses can override this to return a subclass of the setup state. Parameters app (Flask) – options (dict) – first_registration (bool) – Return type flask.blueprints.BlueprintSetupState
flask.api.index#flask.Blueprint.make_setup_state
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.Blueprint.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.Blueprint.patch
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.Blueprint.post
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.Blueprint.put
record(func) Registers a function that is called when the blueprint is registered on the application. This function is called with the state as argument as returned by the make_setup_state() method. Parameters func (Callable) – Return type None
flask.api.index#flask.Blueprint.record
record_once(func) Works like record() but wraps the function in another function that will ensure the function is only called once. If the blueprint is registered a second time on the application, the function passed is not called. Parameters func (Callable) – Return type None
flask.api.index#flask.Blueprint.record_once
register(app, options) Called by Flask.register_blueprint() to register all views and callbacks registered on the blueprint with the application. Creates a BlueprintSetupState and calls each record() callbackwith it. Parameters app (Flask) – The application this blueprint is being registered with. options (dict) – Keyword arguments forwarded from register_blueprint(). first_registration – Whether this is the first time this blueprint has been registered on the application. Return type None
flask.api.index#flask.Blueprint.register
register_blueprint(blueprint, **options) Register a Blueprint on this blueprint. Keyword arguments passed to this method will override the defaults set on the blueprint. New in version 2.0. Parameters blueprint (flask.blueprints.Blueprint) – options (Any) – Return type None
flask.api.index#flask.Blueprint.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.Blueprint.register_error_handler
root_path Absolute path to the package on the filesystem. Used to look up resources contained in the package.
flask.api.index#flask.Blueprint.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.Blueprint.route
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.Blueprint.send_static_file
teardown_app_request(f) Like Flask.teardown_request() but for a blueprint. Such a function is executed when tearing down each request, even if outside of the blueprint. Parameters f (Callable[[Optional[BaseException]], Response]) – Return type Callable[[Optional[BaseException]], Response]
flask.api.index#flask.Blueprint.teardown_app_request
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.Blueprint.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.Blueprint.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.Blueprint.template_context_processors
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.Blueprint.template_folder
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.Blueprint.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.Blueprint.url_default_functions
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.Blueprint.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.Blueprint.url_value_preprocessors
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.Blueprint.view_functions
class flask.blueprints.BlueprintSetupState(blueprint, app, options, first_registration) Temporary holder object for registering a blueprint with the application. An instance of this class is created by the make_setup_state() method and later passed to all register callback functions. Parameters blueprint (Blueprint) – app (Flask) – options (Any) – first_registration (bool) – Return type None add_url_rule(rule, endpoint=None, view_func=None, **options) A helper method to register a rule (and optionally a view function) to the application. The endpoint is automatically prefixed with the blueprint’s name. Parameters rule (str) – endpoint (Optional[str]) – view_func (Optional[Callable]) – options (Any) – Return type None app a reference to the current application blueprint a reference to the blueprint that created this setup state. first_registration as blueprints can be registered multiple times with the application and not everything wants to be registered multiple times on it, this attribute can be used to figure out if the blueprint was registered in the past already. options a dictionary with all options that were passed to the register_blueprint() method. subdomain The subdomain that the blueprint should be active for, None otherwise. url_defaults A dictionary with URL defaults that is added to each and every URL that was defined with the blueprint. url_prefix The prefix that should be used for all URLs defined on the blueprint.
flask.api.index#flask.blueprints.BlueprintSetupState
add_url_rule(rule, endpoint=None, view_func=None, **options) A helper method to register a rule (and optionally a view function) to the application. The endpoint is automatically prefixed with the blueprint’s name. Parameters rule (str) – endpoint (Optional[str]) – view_func (Optional[Callable]) – options (Any) – Return type None
flask.api.index#flask.blueprints.BlueprintSetupState.add_url_rule
app a reference to the current application
flask.api.index#flask.blueprints.BlueprintSetupState.app
blueprint a reference to the blueprint that created this setup state.
flask.api.index#flask.blueprints.BlueprintSetupState.blueprint
first_registration as blueprints can be registered multiple times with the application and not everything wants to be registered multiple times on it, this attribute can be used to figure out if the blueprint was registered in the past already.
flask.api.index#flask.blueprints.BlueprintSetupState.first_registration
options a dictionary with all options that were passed to the register_blueprint() method.
flask.api.index#flask.blueprints.BlueprintSetupState.options
subdomain The subdomain that the blueprint should be active for, None otherwise.
flask.api.index#flask.blueprints.BlueprintSetupState.subdomain
url_defaults A dictionary with URL defaults that is added to each and every URL that was defined with the blueprint.
flask.api.index#flask.blueprints.BlueprintSetupState.url_defaults
url_prefix The prefix that should be used for all URLs defined on the blueprint.
flask.api.index#flask.blueprints.BlueprintSetupState.url_prefix
Caching When your application runs slow, throw some caches in. Well, at least it’s the easiest way to speed up things. What does a cache do? Say you have a function that takes some time to complete but the results would still be good enough if they were 5 minutes old. So then the idea is that you actually put the result of that calculation into a cache for some time. Flask itself does not provide caching for you, but Flask-Caching, an extension for Flask does. Flask-Caching supports various backends, and it is even possible to develop your own caching backend.
flask.patterns.caching.index
CGI If all other deployment methods do not work, CGI will work for sure. CGI is supported by all major servers but usually has a sub-optimal performance. This is also the way you can use a Flask application on Google’s App Engine, where execution happens in a CGI-like environment. Watch Out Please make sure in advance that any app.run() calls you might have in your application file are inside an if __name__ == '__main__': block or moved to a separate file. Just make sure it’s not called because this will always start a local WSGI server which we do not want if we deploy that application to CGI / app engine. With CGI, you will also have to make sure that your code does not contain any print statements, or that sys.stdout is overridden by something that doesn’t write into the HTTP response. Creating a .cgi file First you need to create the CGI application file. Let’s call it yourapplication.cgi: #!/usr/bin/python from wsgiref.handlers import CGIHandler from yourapplication import app CGIHandler().run(app) Server Setup Usually there are two ways to configure the server. Either just copy the .cgi into a cgi-bin (and use mod_rewrite or something similar to rewrite the URL) or let the server point to the file directly. In Apache for example you can put something like this into the config: ScriptAlias /app /path/to/the/application.cgi On shared webhosting, though, you might not have access to your Apache config. In this case, a file called .htaccess, sitting in the public directory you want your app to be available, works too but the ScriptAlias directive won’t work in that case: RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f # Don't interfere with static files RewriteRule ^(.*)$ /path/to/the/application.cgi/$1 [L] For more information consult the documentation of your webserver.
flask.deploying.cgi.index
Changes Version 2.0.1 Unreleased Re-add the filename parameter in send_from_directory. The filename parameter has been renamed to path, the old name is deprecated. #4019 Version 2.0.0 Released 2021-05-11 Drop support for Python 2 and 3.5. Bump minimum versions of other Pallets projects: Werkzeug >= 2, Jinja2 >= 3, MarkupSafe >= 2, ItsDangerous >= 2, Click >= 8. Be sure to check the change logs for each project. For better compatibility with other applications (e.g. Celery) that still require Click 7, there is no hard dependency on Click 8 yet, but using Click 7 will trigger a DeprecationWarning and Flask 2.1 will depend on Click 8. JSON support no longer uses simplejson. To use another JSON module, override app.json_encoder and json_decoder. #3555 The encoding option to JSON functions is deprecated. #3562 Passing script_info to app factory functions is deprecated. This was not portable outside the flask command. Use click.get_current_context().obj if it’s needed. #3552 The CLI shows better error messages when the app failed to load when looking up commands. #2741 Add sessions.SessionInterface.get_cookie_name() to allow setting the session cookie name dynamically. #3369 Add Config.from_file() to load config using arbitrary file loaders, such as toml.load or json.load. Config.from_json() is deprecated in favor of this. #3398 The flask run command will only defer errors on reload. Errors present during the initial call will cause the server to exit with the traceback immediately. #3431 send_file() raises a ValueError when passed an io object in text mode. Previously, it would respond with 200 OK and an empty file. #3358 When using ad-hoc certificates, check for the cryptography library instead of PyOpenSSL. #3492 When specifying a factory function with FLASK_APP, keyword argument can be passed. #3553 When loading a .env or .flaskenv file, the current working directory is no longer changed to the location of the file. #3560 When returning a (response, headers) tuple from a view, the headers replace rather than extend existing headers on the response. For example, this allows setting the Content-Type for jsonify(). Use response.headers.extend() if extending is desired. #3628 The Scaffold class provides a common API for the Flask and Blueprint classes. Blueprint information is stored in attributes just like Flask, rather than opaque lambda functions. This is intended to improve consistency and maintainability. #3215 Include samesite and secure options when removing the session cookie. #3726 Support passing a pathlib.Path to static_folder. #3579 send_file and send_from_directory are wrappers around the implementations in werkzeug.utils. #3828 Some send_file parameters have been renamed, the old names are deprecated. attachment_filename is renamed to download_name. cache_timeout is renamed to max_age. add_etags is renamed to etag. #3828, #3883 send_file passes download_name even if as_attachment=False by using Content-Disposition: inline. #3828 send_file sets conditional=True and max_age=None by default. Cache-Control is set to no-cache if max_age is not set, otherwise public. This tells browsers to validate conditional requests instead of using a timed cache. #3828 helpers.safe_join is deprecated. Use werkzeug.utils.safe_join instead. #3828 The request context does route matching before opening the session. This could allow a session interface to change behavior based on request.endpoint. #3776 Use Jinja’s implementation of the |tojson filter. #3881 Add route decorators for common HTTP methods. For example, @app.post("/login") is a shortcut for @app.route("/login", methods=["POST"]). #3907 Support async views, error handlers, before and after request, and teardown functions. #3412 Support nesting blueprints. #593, #1548, #3923 Set the default encoding to “UTF-8” when loading .env and .flaskenv files to allow to use non-ASCII characters. #3931 flask shell sets up tab and history completion like the default python shell if readline is installed. #3941 helpers.total_seconds() is deprecated. Use timedelta.total_seconds() instead. #3962 Add type hinting. #3973. Version 1.1.2 Released 2020-04-03 Work around an issue when running the flask command with an external debugger on Windows. #3297 The static route will not catch all URLs if the Flask static_folder argument ends with a slash. #3452 Version 1.1.1 Released 2019-07-08 The flask.json_available flag was added back for compatibility with some extensions. It will raise a deprecation warning when used, and will be removed in version 2.0.0. #3288 Version 1.1.0 Released 2019-07-04 Bump minimum Werkzeug version to >= 0.15. Drop support for Python 3.4. Error handlers for InternalServerError or 500 will always be passed an instance of InternalServerError. If they are invoked due to an unhandled exception, that original exception is now available as e.original_exception rather than being passed directly to the handler. The same is true if the handler is for the base HTTPException. This makes error handler behavior more consistent. #3266 Flask.finalize_request() is called for all unhandled exceptions even if there is no 500 error handler. Flask.logger takes the same name as Flask.name (the value passed as Flask(import_name). This reverts 1.0’s behavior of always logging to "flask.app", in order to support multiple apps in the same process. A warning will be shown if old configuration is detected that needs to be moved. #2866 flask.RequestContext.copy() includes the current session object in the request context copy. This prevents session pointing to an out-of-date object. #2935 Using built-in RequestContext, unprintable Unicode characters in Host header will result in a HTTP 400 response and not HTTP 500 as previously. #2994 send_file() supports PathLike objects as described in PEP 0519, to support pathlib in Python 3. #3059 send_file() supports BytesIO partial content. #2957 open_resource() accepts the “rt” file mode. This still does the same thing as “r”. #3163 The MethodView.methods attribute set in a base class is used by subclasses. #3138 Flask.jinja_options is a dict instead of an ImmutableDict to allow easier configuration. Changes must still be made before creating the environment. #3190 Flask’s JSONMixin for the request and response wrappers was moved into Werkzeug. Use Werkzeug’s version with Flask-specific support. This bumps the Werkzeug dependency to >= 0.15. #3125 The flask command entry point is simplified to take advantage of Werkzeug 0.15’s better reloader support. This bumps the Werkzeug dependency to >= 0.15. #3022 Support static_url_path that ends with a forward slash. #3134 Support empty static_folder without requiring setting an empty static_url_path as well. #3124 jsonify() supports dataclasses.dataclass objects. #3195 Allow customizing the Flask.url_map_class used for routing. #3069 The development server port can be set to 0, which tells the OS to pick an available port. #2926 The return value from cli.load_dotenv() is more consistent with the documentation. It will return False if python-dotenv is not installed, or if the given path isn’t a file. #2937 Signaling support has a stub for the connect_via method when the Blinker library is not installed. #3208 Add an --extra-files option to the flask run CLI command to specify extra files that will trigger the reloader on change. #2897 Allow returning a dictionary from a view function. Similar to how returning a string will produce a text/html response, returning a dict will call jsonify to produce a application/json response. #3111 Blueprints have a cli Click group like app.cli. CLI commands registered with a blueprint will be available as a group under the flask command. #1357. When using the test client as a context manager (with client:), all preserved request contexts are popped when the block exits, ensuring nested contexts are cleaned up correctly. #3157 Show a better error message when the view return type is not supported. #3214 flask.testing.make_test_environ_builder() has been deprecated in favour of a new class flask.testing.EnvironBuilder. #3232 The flask run command no longer fails if Python is not built with SSL support. Using the --cert option will show an appropriate error message. #3211 URL matching now occurs after the request context is pushed, rather than when it’s created. This allows custom URL converters to access the app and request contexts, such as to query a database for an id. #3088 Version 1.0.4 Released 2019-07-04 The key information for BadRequestKeyError is no longer cleared outside debug mode, so error handlers can still access it. This requires upgrading to Werkzeug 0.15.5. #3249 send_file url quotes the “:” and “/” characters for more compatible UTF-8 filename support in some browsers. #3074 Fixes for PEP451 import loaders and pytest 5.x. #3275 Show message about dotenv on stderr instead of stdout. #3285 Version 1.0.3 Released 2019-05-17 send_file() encodes filenames as ASCII instead of Latin-1 (ISO-8859-1). This fixes compatibility with Gunicorn, which is stricter about header encodings than PEP 3333. #2766 Allow custom CLIs using FlaskGroup to set the debug flag without it always being overwritten based on environment variables. #2765 flask --version outputs Werkzeug’s version and simplifies the Python version. #2825 send_file() handles an attachment_filename that is a native Python 2 string (bytes) with UTF-8 coded bytes. #2933 A catch-all error handler registered for HTTPException will not handle RoutingException, which is used internally during routing. This fixes the unexpected behavior that had been introduced in 1.0. #2986 Passing the json argument to app.test_client does not push/pop an extra app context. #2900 Version 1.0.2 Released 2018-05-02 Fix more backwards compatibility issues with merging slashes between a blueprint prefix and route. #2748 Fix error with flask routes command when there are no routes. #2751 Version 1.0.1 Released 2018-04-29 Fix registering partials (with no __name__) as view functions. #2730 Don’t treat lists returned from view functions the same as tuples. Only tuples are interpreted as response data. #2736 Extra slashes between a blueprint’s url_prefix and a route URL are merged. This fixes some backwards compatibility issues with the change in 1.0. #2731, #2742 Only trap BadRequestKeyError errors in debug mode, not all BadRequest errors. This allows abort(400) to continue working as expected. #2735 The FLASK_SKIP_DOTENV environment variable can be set to 1 to skip automatically loading dotenv files. #2722 Version 1.0 Released 2018-04-26 Python 2.6 and 3.3 are no longer supported. Bump minimum dependency versions to the latest stable versions: Werkzeug >= 0.14, Jinja >= 2.10, itsdangerous >= 0.24, Click >= 5.1. #2586 Skip app.run when a Flask application is run from the command line. This avoids some behavior that was confusing to debug. Change the default for JSONIFY_PRETTYPRINT_REGULAR to False. jsonify() returns a compact format by default, and an indented format in debug mode. #2193 Flask.__init__ accepts the host_matching argument and sets it on url_map. #1559 Flask.__init__ accepts the static_host argument and passes it as the host argument when defining the static route. #1559 send_file() supports Unicode in attachment_filename. #2223 Pass _scheme argument from url_for() to handle_url_build_error(). #2017 add_url_rule() accepts the provide_automatic_options argument to disable adding the OPTIONS method. #1489 MethodView subclasses inherit method handlers from base classes. #1936 Errors caused while opening the session at the beginning of the request are handled by the app’s error handlers. #2254 Blueprints gained json_encoder and json_decoder attributes to override the app’s encoder and decoder. #1898 Flask.make_response() raises TypeError instead of ValueError for bad response types. The error messages have been improved to describe why the type is invalid. #2256 Add routes CLI command to output routes registered on the application. #2259 Show warning when session cookie domain is a bare hostname or an IP address, as these may not behave properly in some browsers, such as Chrome. #2282 Allow IP address as exact session cookie domain. #2282 SESSION_COOKIE_DOMAIN is set if it is detected through SERVER_NAME. #2282 Auto-detect zero-argument app factory called create_app or make_app from FLASK_APP. #2297 Factory functions are not required to take a script_info parameter to work with the flask command. If they take a single parameter or a parameter named script_info, the ScriptInfo object will be passed. #2319 FLASK_APP can be set to an app factory, with arguments if needed, for example FLASK_APP=myproject.app:create_app('dev'). #2326 FLASK_APP can point to local packages that are not installed in editable mode, although pip install -e is still preferred. #2414 The View class attribute provide_automatic_options is set in as_view(), to be detected by add_url_rule(). #2316 Error handling will try handlers registered for blueprint, code, app, code, blueprint, exception, app, exception. #2314 Cookie is added to the response’s Vary header if the session is accessed at all during the request (and not deleted). #2288 test_request_context() accepts subdomain and url_scheme arguments for use when building the base URL. #1621 Set APPLICATION_ROOT to '/' by default. This was already the implicit default when it was set to None. TRAP_BAD_REQUEST_ERRORS is enabled by default in debug mode. BadRequestKeyError has a message with the bad key in debug mode instead of the generic bad request message. #2348 Allow registering new tags with TaggedJSONSerializer to support storing other types in the session cookie. #2352 Only open the session if the request has not been pushed onto the context stack yet. This allows stream_with_context() generators to access the same session that the containing view uses. #2354 Add json keyword argument for the test client request methods. This will dump the given object as JSON and set the appropriate content type. #2358 Extract JSON handling to a mixin applied to both the Request and Response classes. This adds the is_json() and get_json() methods to the response to make testing JSON response much easier. #2358 Removed error handler caching because it caused unexpected results for some exception inheritance hierarchies. Register handlers explicitly for each exception if you want to avoid traversing the MRO. #2362 Fix incorrect JSON encoding of aware, non-UTC datetimes. #2374 Template auto reloading will honor debug mode even even if jinja_env was already accessed. #2373 The following old deprecated code was removed. #2385 flask.ext - import extensions directly by their name instead of through the flask.ext namespace. For example, import flask.ext.sqlalchemy becomes import flask_sqlalchemy. Flask.init_jinja_globals - extend Flask.create_jinja_environment() instead. Flask.error_handlers - tracked by Flask.error_handler_spec, use Flask.errorhandler() to register handlers. Flask.request_globals_class - use Flask.app_ctx_globals_class instead. Flask.static_path - use Flask.static_url_path instead. Request.module - use Request.blueprint instead. The Request.json property is no longer deprecated. #1421 Support passing a EnvironBuilder or dict to test_client.open. #2412 The flask command and Flask.run() will load environment variables from .env and .flaskenv files if python-dotenv is installed. #2416 When passing a full URL to the test client, the scheme in the URL is used instead of PREFERRED_URL_SCHEME. #2430 Flask.logger has been simplified. LOGGER_NAME and LOGGER_HANDLER_POLICY config was removed. The logger is always named flask.app. The level is only set on first access, it doesn’t check Flask.debug each time. Only one format is used, not different ones depending on Flask.debug. No handlers are removed, and a handler is only added if no handlers are already configured. #2436 Blueprint view function names may not contain dots. #2450 Fix a ValueError caused by invalid Range requests in some cases. #2526 The development server uses threads by default. #2529 Loading config files with silent=True will ignore ENOTDIR errors. #2581 Pass --cert and --key options to flask run to run the development server over HTTPS. #2606 Added SESSION_COOKIE_SAMESITE to control the SameSite attribute on the session cookie. #2607 Added test_cli_runner() to create a Click runner that can invoke Flask CLI commands for testing. #2636 Subdomain matching is disabled by default and setting SERVER_NAME does not implicitly enable it. It can be enabled by passing subdomain_matching=True to the Flask constructor. #2635 A single trailing slash is stripped from the blueprint url_prefix when it is registered with the app. #2629 Request.get_json() doesn’t cache the result if parsing fails when silent is true. #2651 Request.get_json() no longer accepts arbitrary encodings. Incoming JSON should be encoded using UTF-8 per RFC 8259, but Flask will autodetect UTF-8, -16, or -32. #2691 Added MAX_COOKIE_SIZE and Response.max_cookie_size to control when Werkzeug warns about large cookies that browsers may ignore. #2693 Updated documentation theme to make docs look better in small windows. #2709 Rewrote the tutorial docs and example project to take a more structured approach to help new users avoid common pitfalls. #2676 Version 0.12.5 Released 2020-02-10 Pin Werkzeug to < 1.0.0. #3497 Version 0.12.4 Released 2018-04-29 Repackage 0.12.3 to fix package layout issue. #2728 Version 0.12.3 Released 2018-04-26 Request.get_json() no longer accepts arbitrary encodings. Incoming JSON should be encoded using UTF-8 per RFC 8259, but Flask will autodetect UTF-8, -16, or -32. #2692 Fix a Python warning about imports when using python -m flask. #2666 Fix a ValueError caused by invalid Range requests in some cases. Version 0.12.2 Released 2017-05-16 Fix a bug in safe_join on Windows. Version 0.12.1 Released 2017-03-31 Prevent flask run from showing a NoAppException when an ImportError occurs within the imported application module. Fix encoding behavior of app.config.from_pyfile for Python 3. #2118 Use the SERVER_NAME config if it is present as default values for app.run. #2109, #2152 Call ctx.auto_pop with the exception object instead of None, in the event that a BaseException such as KeyboardInterrupt is raised in a request handler. Version 0.12 Released 2016-12-21, codename Punsch The cli command now responds to --version. Mimetype guessing and ETag generation for file-like objects in send_file has been removed. #104, :pr`1849` Mimetype guessing in send_file now fails loudly and doesn’t fall back to application/octet-stream. #1988 Make flask.safe_join able to join multiple paths like os.path.join #1730 Revert a behavior change that made the dev server crash instead of returning an Internal Server Error. #2006 Correctly invoke response handlers for both regular request dispatching as well as error handlers. Disable logger propagation by default for the app logger. Add support for range requests in send_file. app.test_client includes preset default environment, which can now be directly set, instead of per client.get. Fix crash when running under PyPy3. #1814 Version 0.11.1 Released 2016-06-07 Fixed a bug that prevented FLASK_APP=foobar/__init__.py from working. #1872 Version 0.11 Released 2016-05-29, codename Absinthe Added support to serializing top-level arrays to flask.jsonify(). This introduces a security risk in ancient browsers. Added before_render_template signal. Added **kwargs to flask.Test.test_client() to support passing additional keyword arguments to the constructor of flask.Flask.test_client_class. Added SESSION_REFRESH_EACH_REQUEST config key that controls the set-cookie behavior. If set to True a permanent session will be refreshed each request and get their lifetime extended, if set to False it will only be modified if the session actually modifies. Non permanent sessions are not affected by this and will always expire if the browser window closes. Made Flask support custom JSON mimetypes for incoming data. Added support for returning tuples in the form (response, headers) from a view function. Added flask.Config.from_json(). Added flask.Flask.config_class. Added flask.Config.get_namespace(). Templates are no longer automatically reloaded outside of debug mode. This can be configured with the new TEMPLATES_AUTO_RELOAD config key. Added a workaround for a limitation in Python 3.3’s namespace loader. Added support for explicit root paths when using Python 3.3’s namespace packages. Added flask and the flask.cli module to start the local debug server through the click CLI system. This is recommended over the old flask.run() method as it works faster and more reliable due to a different design and also replaces Flask-Script. Error handlers that match specific classes are now checked first, thereby allowing catching exceptions that are subclasses of HTTP exceptions (in werkzeug.exceptions). This makes it possible for an extension author to create exceptions that will by default result in the HTTP error of their choosing, but may be caught with a custom error handler if desired. Added flask.Config.from_mapping(). Flask will now log by default even if debug is disabled. The log format is now hardcoded but the default log handling can be disabled through the LOGGER_HANDLER_POLICY configuration key. Removed deprecated module functionality. Added the EXPLAIN_TEMPLATE_LOADING config flag which when enabled will instruct Flask to explain how it locates templates. This should help users debug when the wrong templates are loaded. Enforce blueprint handling in the order they were registered for template loading. Ported test suite to py.test. Deprecated request.json in favour of request.get_json(). Add “pretty” and “compressed” separators definitions in jsonify() method. Reduces JSON response size when JSONIFY_PRETTYPRINT_REGULAR=False by removing unnecessary white space included by default after separators. JSON responses are now terminated with a newline character, because it is a convention that UNIX text files end with a newline and some clients don’t deal well when this newline is missing. This came up originally as a part of https://github.com/postmanlabs/httpbin/issues/168. #1262 The automatically provided OPTIONS method is now correctly disabled if the user registered an overriding rule with the lowercase-version options. #1288 flask.json.jsonify now supports the datetime.date type. #1326 Don’t leak exception info of already caught exceptions to context teardown handlers. #1393 Allow custom Jinja environment subclasses. #1422 Updated extension dev guidelines. flask.g now has pop() and setdefault methods. Turn on autoescape for flask.templating.render_template_string by default. #1515 flask.ext is now deprecated. #1484 send_from_directory now raises BadRequest if the filename is invalid on the server OS. #1763 Added the JSONIFY_MIMETYPE configuration variable. #1728 Exceptions during teardown handling will no longer leave bad application contexts lingering around. Fixed broken test_appcontext_signals() test case. Raise an AttributeError in flask.helpers.find_package() with a useful message explaining why it is raised when a PEP 302 import hook is used without an is_package() method. Fixed an issue causing exceptions raised before entering a request or app context to be passed to teardown handlers. Fixed an issue with query parameters getting removed from requests in the test client when absolute URLs were requested. Made @before_first_request into a decorator as intended. Fixed an etags bug when sending a file streams with a name. Fixed send_from_directory not expanding to the application root path correctly. Changed logic of before first request handlers to flip the flag after invoking. This will allow some uses that are potentially dangerous but should probably be permitted. Fixed Python 3 bug when a handler from app.url_build_error_handlers reraises the BuildError. Version 0.10.1 Released 2013-06-14 Fixed an issue where |tojson was not quoting single quotes which made the filter not work properly in HTML attributes. Now it’s possible to use that filter in single quoted attributes. This should make using that filter with angular.js easier. Added support for byte strings back to the session system. This broke compatibility with the common case of people putting binary data for token verification into the session. Fixed an issue where registering the same method twice for the same endpoint would trigger an exception incorrectly. Version 0.10 Released 2013-06-13, codename Limoncello Changed default cookie serialization format from pickle to JSON to limit the impact an attacker can do if the secret key leaks. Added template_test methods in addition to the already existing template_filter method family. Added template_global methods in addition to the already existing template_filter method family. Set the content-length header for x-sendfile. tojson filter now does not escape script blocks in HTML5 parsers. tojson used in templates is now safe by default due. This was allowed due to the different escaping behavior. Flask will now raise an error if you attempt to register a new function on an already used endpoint. Added wrapper module around simplejson and added default serialization of datetime objects. This allows much easier customization of how JSON is handled by Flask or any Flask extension. Removed deprecated internal flask.session module alias. Use flask.sessions instead to get the session module. This is not to be confused with flask.session the session proxy. Templates can now be rendered without request context. The behavior is slightly different as the request, session and g objects will not be available and blueprint’s context processors are not called. The config object is now available to the template as a real global and not through a context processor which makes it available even in imported templates by default. Added an option to generate non-ascii encoded JSON which should result in less bytes being transmitted over the network. It’s disabled by default to not cause confusion with existing libraries that might expect flask.json.dumps to return bytes by default. flask.g is now stored on the app context instead of the request context. flask.g now gained a get() method for not erroring out on non existing items. flask.g now can be used with the in operator to see what’s defined and it now is iterable and will yield all attributes stored. flask.Flask.request_globals_class got renamed to flask.Flask.app_ctx_globals_class which is a better name to what it does since 0.10. request, session and g are now also added as proxies to the template context which makes them available in imported templates. One has to be very careful with those though because usage outside of macros might cause caching. Flask will no longer invoke the wrong error handlers if a proxy exception is passed through. Added a workaround for chrome’s cookies in localhost not working as intended with domain names. Changed logic for picking defaults for cookie values from sessions to work better with Google Chrome. Added message_flashed signal that simplifies flashing testing. Added support for copying of request contexts for better working with greenlets. Removed custom JSON HTTP exception subclasses. If you were relying on them you can reintroduce them again yourself trivially. Using them however is strongly discouraged as the interface was flawed. Python requirements changed: requiring Python 2.6 or 2.7 now to prepare for Python 3.3 port. Changed how the teardown system is informed about exceptions. This is now more reliable in case something handles an exception halfway through the error handling process. Request context preservation in debug mode now keeps the exception information around which means that teardown handlers are able to distinguish error from success cases. Added the JSONIFY_PRETTYPRINT_REGULAR configuration variable. Flask now orders JSON keys by default to not trash HTTP caches due to different hash seeds between different workers. Added appcontext_pushed and appcontext_popped signals. The builtin run method now takes the SERVER_NAME into account when picking the default port to run on. Added flask.request.get_json() as a replacement for the old flask.request.json property. Version 0.9 Released 2012-07-01, codename Campari The flask.Request.on_json_loading_failed() now returns a JSON formatted response by default. The flask.url_for() function now can generate anchors to the generated links. The flask.url_for() function now can also explicitly generate URL rules specific to a given HTTP method. Logger now only returns the debug log setting if it was not set explicitly. Unregister a circular dependency between the WSGI environment and the request object when shutting down the request. This means that environ werkzeug.request will be None after the response was returned to the WSGI server but has the advantage that the garbage collector is not needed on CPython to tear down the request unless the user created circular dependencies themselves. Session is now stored after callbacks so that if the session payload is stored in the session you can still modify it in an after request callback. The flask.Flask class will avoid importing the provided import name if it can (the required first parameter), to benefit tools which build Flask instances programmatically. The Flask class will fall back to using import on systems with custom module hooks, e.g. Google App Engine, or when the import name is inside a zip archive (usually a .egg) prior to Python 2.7. Blueprints now have a decorator to add custom template filters application wide, flask.Blueprint.app_template_filter(). The Flask and Blueprint classes now have a non-decorator method for adding custom template filters application wide, flask.Flask.add_template_filter() and flask.Blueprint.add_app_template_filter(). The flask.get_flashed_messages() function now allows rendering flashed message categories in separate blocks, through a category_filter argument. The flask.Flask.run() method now accepts None for host and port arguments, using default values when None. This allows for calling run using configuration values, e.g. app.run(app.config.get('MYHOST'), app.config.get('MYPORT')), with proper behavior whether or not a config file is provided. The flask.render_template() method now accepts a either an iterable of template names or a single template name. Previously, it only accepted a single template name. On an iterable, the first template found is rendered. Added flask.Flask.app_context() which works very similar to the request context but only provides access to the current application. This also adds support for URL generation without an active request context. View functions can now return a tuple with the first instance being an instance of flask.Response. This allows for returning jsonify(error="error msg"), 400 from a view function. Flask and Blueprint now provide a get_send_file_max_age() hook for subclasses to override behavior of serving static files from Flask when using flask.Flask.send_static_file() (used for the default static file handler) and send_file(). This hook is provided a filename, which for example allows changing cache controls by file extension. The default max-age for send_file and static files can be configured through a new SEND_FILE_MAX_AGE_DEFAULT configuration variable, which is used in the default get_send_file_max_age implementation. Fixed an assumption in sessions implementation which could break message flashing on sessions implementations which use external storage. Changed the behavior of tuple return values from functions. They are no longer arguments to the response object, they now have a defined meaning. Added flask.Flask.request_globals_class to allow a specific class to be used on creation of the g instance of each request. Added required_methods attribute to view functions to force-add methods on registration. Added flask.after_this_request(). Added flask.stream_with_context() and the ability to push contexts multiple times without producing unexpected behavior. Version 0.8.1 Released 2012-07-01 Fixed an issue with the undocumented flask.session module to not work properly on Python 2.5. It should not be used but did cause some problems for package managers. Version 0.8 Released 2011-09-29, codename Rakija Refactored session support into a session interface so that the implementation of the sessions can be changed without having to override the Flask class. Empty session cookies are now deleted properly automatically. View functions can now opt out of getting the automatic OPTIONS implementation. HTTP exceptions and Bad Request errors can now be trapped so that they show up normally in the traceback. Flask in debug mode is now detecting some common problems and tries to warn you about them. Flask in debug mode will now complain with an assertion error if a view was attached after the first request was handled. This gives earlier feedback when users forget to import view code ahead of time. Added the ability to register callbacks that are only triggered once at the beginning of the first request. (Flask.before_first_request()) Malformed JSON data will now trigger a bad request HTTP exception instead of a value error which usually would result in a 500 internal server error if not handled. This is a backwards incompatible change. Applications now not only have a root path where the resources and modules are located but also an instance path which is the designated place to drop files that are modified at runtime (uploads etc.). Also this is conceptually only instance depending and outside version control so it’s the perfect place to put configuration files etc. Added the APPLICATION_ROOT configuration variable. Implemented session_transaction() to easily modify sessions from the test environment. Refactored test client internally. The APPLICATION_ROOT configuration variable as well as SERVER_NAME are now properly used by the test client as defaults. Added flask.views.View.decorators to support simpler decorating of pluggable (class-based) views. Fixed an issue where the test client if used with the “with” statement did not trigger the execution of the teardown handlers. Added finer control over the session cookie parameters. HEAD requests to a method view now automatically dispatch to the get method if no handler was implemented. Implemented the virtual flask.ext package to import extensions from. The context preservation on exceptions is now an integral component of Flask itself and no longer of the test client. This cleaned up some internal logic and lowers the odds of runaway request contexts in unittests. Fixed the Jinja2 environment’s list_templates method not returning the correct names when blueprints or modules were involved. Version 0.7.2 Released 2011-07-06 Fixed an issue with URL processors not properly working on blueprints. Version 0.7.1 Released 2011-06-29 Added missing future import that broke 2.5 compatibility. Fixed an infinite redirect issue with blueprints. Version 0.7 Released 2011-06-28, codename Grappa Added make_default_options_response() which can be used by subclasses to alter the default behavior for OPTIONS responses. Unbound locals now raise a proper RuntimeError instead of an AttributeError. Mimetype guessing and etag support based on file objects is now deprecated for flask.send_file() because it was unreliable. Pass filenames instead or attach your own etags and provide a proper mimetype by hand. Static file handling for modules now requires the name of the static folder to be supplied explicitly. The previous autodetection was not reliable and caused issues on Google’s App Engine. Until 1.0 the old behavior will continue to work but issue dependency warnings. Fixed a problem for Flask to run on jython. Added a PROPAGATE_EXCEPTIONS configuration variable that can be used to flip the setting of exception propagation which previously was linked to DEBUG alone and is now linked to either DEBUG or TESTING. Flask no longer internally depends on rules being added through the add_url_rule function and can now also accept regular werkzeug rules added to the url map. Added an endpoint method to the flask application object which allows one to register a callback to an arbitrary endpoint with a decorator. Use Last-Modified for static file sending instead of Date which was incorrectly introduced in 0.6. Added create_jinja_loader to override the loader creation process. Implemented a silent flag for config.from_pyfile. Added teardown_request decorator, for functions that should run at the end of a request regardless of whether an exception occurred. Also the behavior for after_request was changed. It’s now no longer executed when an exception is raised. Implemented flask.has_request_context() Deprecated init_jinja_globals. Override the create_jinja_environment() method instead to achieve the same functionality. Added flask.safe_join() The automatic JSON request data unpacking now looks at the charset mimetype parameter. Don’t modify the session on flask.get_flashed_messages() if there are no messages in the session. before_request handlers are now able to abort requests with errors. It is not possible to define user exception handlers. That way you can provide custom error messages from a central hub for certain errors that might occur during request processing (for instance database connection errors, timeouts from remote resources etc.). Blueprints can provide blueprint specific error handlers. Implemented generic class-based views. Version 0.6.1 Released 2010-12-31 Fixed an issue where the default OPTIONS response was not exposing all valid methods in the Allow header. Jinja2 template loading syntax now allows “./” in front of a template load path. Previously this caused issues with module setups. Fixed an issue where the subdomain setting for modules was ignored for the static folder. Fixed a security problem that allowed clients to download arbitrary files if the host server was a windows based operating system and the client uses backslashes to escape the directory the files where exposed from. Version 0.6 Released 2010-07-27, codename Whisky After request functions are now called in reverse order of registration. OPTIONS is now automatically implemented by Flask unless the application explicitly adds ‘OPTIONS’ as method to the URL rule. In this case no automatic OPTIONS handling kicks in. Static rules are now even in place if there is no static folder for the module. This was implemented to aid GAE which will remove the static folder if it’s part of a mapping in the .yml file. The config is now available in the templates as config. Context processors will no longer override values passed directly to the render function. Added the ability to limit the incoming request data with the new MAX_CONTENT_LENGTH configuration value. The endpoint for the flask.Module.add_url_rule() method is now optional to be consistent with the function of the same name on the application object. Added a flask.make_response() function that simplifies creating response object instances in views. Added signalling support based on blinker. This feature is currently optional and supposed to be used by extensions and applications. If you want to use it, make sure to have blinker installed. Refactored the way URL adapters are created. This process is now fully customizable with the create_url_adapter() method. Modules can now register for a subdomain instead of just an URL prefix. This makes it possible to bind a whole module to a configurable subdomain. Version 0.5.2 Released 2010-07-15 Fixed another issue with loading templates from directories when modules were used. Version 0.5.1 Released 2010-07-06 Fixes an issue with template loading from directories when modules where used. Version 0.5 Released 2010-07-06, codename Calvados Fixed a bug with subdomains that was caused by the inability to specify the server name. The server name can now be set with the SERVER_NAME config key. This key is now also used to set the session cookie cross-subdomain wide. Autoescaping is no longer active for all templates. Instead it is only active for .html, .htm, .xml and .xhtml. Inside templates this behavior can be changed with the autoescape tag. Refactored Flask internally. It now consists of more than a single file. flask.send_file() now emits etags and has the ability to do conditional responses builtin. (temporarily) dropped support for zipped applications. This was a rarely used feature and led to some confusing behavior. Added support for per-package template and static-file directories. Removed support for create_jinja_loader which is no longer used in 0.5 due to the improved module support. Added a helper function to expose files from any directory. Version 0.4 Released 2010-06-18, codename Rakia Added the ability to register application wide error handlers from modules. after_request() handlers are now also invoked if the request dies with an exception and an error handling page kicks in. Test client has not the ability to preserve the request context for a little longer. This can also be used to trigger custom requests that do not pop the request stack for testing. Because the Python standard library caches loggers, the name of the logger is configurable now to better support unittests. Added TESTING switch that can activate unittesting helpers. The logger switches to DEBUG mode now if debug is enabled. Version 0.3.1 Released 2010-05-28 Fixed a error reporting bug with flask.Config.from_envvar() Removed some unused code from flask Release does no longer include development leftover files (.git folder for themes, built documentation in zip and pdf file and some .pyc files) Version 0.3 Released 2010-05-28, codename Schnaps Added support for categories for flashed messages. The application now configures a logging.Handler and will log request handling exceptions to that logger when not in debug mode. This makes it possible to receive mails on server errors for example. Added support for context binding that does not require the use of the with statement for playing in the console. The request context is now available within the with statement making it possible to further push the request context or pop it. Added support for configurations. Version 0.2 Released 2010-05-12, codename J?germeister Various bugfixes Integrated JSON support Added get_template_attribute() helper function. add_url_rule() can now also register a view function. Refactored internal request dispatching. Server listens on 127.0.0.1 by default now to fix issues with chrome. Added external URL support. Added support for send_file() Module support and internal request handling refactoring to better support pluggable applications. Sessions can be set to be permanent now on a per-session basis. Better error reporting on missing secret keys. Added support for Google Appengine. Version 0.1 Released 2010-04-16 First public preview release.
flask.changes.index
class flask.Config(root_path, defaults=None) Works exactly like a dict but provides ways to fill it from files or special dictionaries. There are two common patterns to populate the config. Either you can fill the config from a config file: app.config.from_pyfile('yourconfig.cfg') Or alternatively you can define the configuration options in the module that calls from_object() or provide an import path to a module that should be loaded. It is also possible to tell it to use the same module and with that provide the configuration values just before the call: DEBUG = True SECRET_KEY = 'development key' app.config.from_object(__name__) In both cases (loading from any Python file or loading from modules), only uppercase keys are added to the config. This makes it possible to use lowercase values in the config file for temporary values that are not added to the config or to define the config keys in the same file that implements the application. Probably the most interesting way to load configurations is from an environment variable pointing to a file: app.config.from_envvar('YOURAPPLICATION_SETTINGS') In this case before launching the application you have to set this environment variable to the file you want to use. On Linux and OS X use the export statement: export YOURAPPLICATION_SETTINGS='/path/to/config/file' On windows use set instead. Parameters root_path (str) – path to which files are read relative from. When the config object is created by the application, this is the application’s root_path. defaults (Optional[dict]) – an optional dictionary of default values Return type None from_envvar(variable_name, silent=False) Loads a configuration from an environment variable pointing to a configuration file. This is basically just a shortcut with nicer error messages for this line of code: app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS']) Parameters variable_name (str) – name of the environment variable silent (bool) – set to True if you want silent failure for missing files. Returns bool. True if able to load config, False otherwise. Return type bool from_file(filename, load, silent=False) Update the values in the config from a file that is loaded using the load parameter. The loaded data is passed to the from_mapping() method. import toml app.config.from_file("config.toml", load=toml.load) Parameters filename (str) – The path to the data file. This can be an absolute path or relative to the config root path. load (Callable[[Reader], Mapping] where Reader implements a read method.) – A callable that takes a file handle and returns a mapping of loaded data from the file. silent (bool) – Ignore the file if it doesn’t exist. Return type bool New in version 2.0. from_mapping(mapping=None, **kwargs) Updates the config like update() ignoring items with non-upper keys. Changelog New in version 0.11. Parameters mapping (Optional[Mapping[str, Any]]) – kwargs (Any) – Return type bool from_object(obj) Updates the values from the given object. An object can be of one of the following two types: a string: in this case the object with that name will be imported an actual object reference: that object is used directly Objects are usually either modules or classes. from_object() loads only the uppercase attributes of the module/class. A dict object will not work with from_object() because the keys of a dict are not attributes of the dict class. Example of module-based configuration: app.config.from_object('yourapplication.default_config') from yourapplication import default_config app.config.from_object(default_config) Nothing is done to the object before loading. If the object is a class and has @property attributes, it needs to be instantiated before being passed to this method. You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with from_pyfile() and ideally from a location not within the package because the package might be installed system wide. See Development / Production for an example of class-based configuration using from_object(). Parameters obj (Union[object, str]) – an import name or object Return type None from_pyfile(filename, silent=False) Updates the values in the config from a Python file. This function behaves as if the file was imported as module with the from_object() function. Parameters filename (str) – the filename of the config. This can either be an absolute filename or a filename relative to the root path. silent (bool) – set to True if you want silent failure for missing files. Return type bool Changelog New in version 0.7: silent parameter. get_namespace(namespace, lowercase=True, trim_namespace=True) Returns a dictionary containing a subset of configuration options that match the specified namespace/prefix. Example usage: app.config['IMAGE_STORE_TYPE'] = 'fs' app.config['IMAGE_STORE_PATH'] = '/var/app/images' app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com' image_store_config = app.config.get_namespace('IMAGE_STORE_') The resulting dictionary image_store_config would look like: { 'type': 'fs', 'path': '/var/app/images', 'base_url': 'http://img.website.com' } This is often useful when configuration options map directly to keyword arguments in functions or class constructors. Parameters namespace (str) – a configuration namespace lowercase (bool) – a flag indicating if the keys of the resulting dictionary should be lowercase trim_namespace (bool) – a flag indicating if the keys of the resulting dictionary should not include the namespace Return type Dict[str, Any] Changelog New in version 0.11.
flask.api.index#flask.Config
from_envvar(variable_name, silent=False) Loads a configuration from an environment variable pointing to a configuration file. This is basically just a shortcut with nicer error messages for this line of code: app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS']) Parameters variable_name (str) – name of the environment variable silent (bool) – set to True if you want silent failure for missing files. Returns bool. True if able to load config, False otherwise. Return type bool
flask.api.index#flask.Config.from_envvar
from_file(filename, load, silent=False) Update the values in the config from a file that is loaded using the load parameter. The loaded data is passed to the from_mapping() method. import toml app.config.from_file("config.toml", load=toml.load) Parameters filename (str) – The path to the data file. This can be an absolute path or relative to the config root path. load (Callable[[Reader], Mapping] where Reader implements a read method.) – A callable that takes a file handle and returns a mapping of loaded data from the file. silent (bool) – Ignore the file if it doesn’t exist. Return type bool New in version 2.0.
flask.api.index#flask.Config.from_file
from_mapping(mapping=None, **kwargs) Updates the config like update() ignoring items with non-upper keys. Changelog New in version 0.11. Parameters mapping (Optional[Mapping[str, Any]]) – kwargs (Any) – Return type bool
flask.api.index#flask.Config.from_mapping
from_object(obj) Updates the values from the given object. An object can be of one of the following two types: a string: in this case the object with that name will be imported an actual object reference: that object is used directly Objects are usually either modules or classes. from_object() loads only the uppercase attributes of the module/class. A dict object will not work with from_object() because the keys of a dict are not attributes of the dict class. Example of module-based configuration: app.config.from_object('yourapplication.default_config') from yourapplication import default_config app.config.from_object(default_config) Nothing is done to the object before loading. If the object is a class and has @property attributes, it needs to be instantiated before being passed to this method. You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with from_pyfile() and ideally from a location not within the package because the package might be installed system wide. See Development / Production for an example of class-based configuration using from_object(). Parameters obj (Union[object, str]) – an import name or object Return type None
flask.api.index#flask.Config.from_object
from_pyfile(filename, silent=False) Updates the values in the config from a Python file. This function behaves as if the file was imported as module with the from_object() function. Parameters filename (str) – the filename of the config. This can either be an absolute filename or a filename relative to the root path. silent (bool) – set to True if you want silent failure for missing files. Return type bool Changelog New in version 0.7: silent parameter.
flask.api.index#flask.Config.from_pyfile
get_namespace(namespace, lowercase=True, trim_namespace=True) Returns a dictionary containing a subset of configuration options that match the specified namespace/prefix. Example usage: app.config['IMAGE_STORE_TYPE'] = 'fs' app.config['IMAGE_STORE_PATH'] = '/var/app/images' app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com' image_store_config = app.config.get_namespace('IMAGE_STORE_') The resulting dictionary image_store_config would look like: { 'type': 'fs', 'path': '/var/app/images', 'base_url': 'http://img.website.com' } This is often useful when configuration options map directly to keyword arguments in functions or class constructors. Parameters namespace (str) – a configuration namespace lowercase (bool) – a flag indicating if the keys of the resulting dictionary should be lowercase trim_namespace (bool) – a flag indicating if the keys of the resulting dictionary should not include the namespace Return type Dict[str, Any] Changelog New in version 0.11.
flask.api.index#flask.Config.get_namespace
flask.copy_current_request_context(f) A helper function that decorates a function to retain the current request context. This is useful when working with greenlets. The moment the function is decorated a copy of the request context is created and then pushed when the function is called. The current session is also included in the copied request context. Example: import gevent from flask import copy_current_request_context @app.route('/') def index(): @copy_current_request_context def do_some_work(): # do some work here, it can access flask.request or # flask.session like you would otherwise in the view function. ... gevent.spawn(do_some_work) return 'Regular response' Changelog New in version 0.10. Parameters f (Callable) – Return type Callable
flask.api.index#flask.copy_current_request_context
DEBUG Whether debug mode is enabled. When using flask run to start the development server, an interactive debugger will be shown for unhandled exceptions, and the server will be reloaded when code changes. The debug attribute maps to this config key. This is enabled when ENV is 'development' and is overridden by the FLASK_DEBUG environment variable. It may not behave as expected if set in code. Do not enable debug mode when deploying in production. Default: True if ENV is 'development', or False otherwise.
flask.config.index#DEBUG
flask.json.dump(obj, fp, app=None, **kwargs) Serialize an object to JSON written to a file object. Takes the same arguments as the built-in json.dump(), with some defaults from application configuration. Parameters obj (Any) – Object to serialize to JSON. fp (IO[str]) – File object to write JSON to. app (Optional[Flask]) – Use this app’s config instead of the active app context or defaults. kwargs (Any) – Extra arguments passed to json.dump(). Return type None Changed in version 2.0: Writing to a binary file, and the encoding argument, is deprecated and will be removed in Flask 2.1.
flask.api.index#flask.json.dump
flask.json.dumps(obj, app=None, **kwargs) Serialize an object to a string of JSON. Takes the same arguments as the built-in json.dumps(), with some defaults from application configuration. Parameters obj (Any) – Object to serialize to JSON. app (Optional[Flask]) – Use this app’s config instead of the active app context or defaults. kwargs (Any) – Extra arguments passed to json.dumps(). Return type str Changed in version 2.0: encoding is deprecated and will be removed in Flask 2.1. Changelog Changed in version 1.0.3: app can be passed directly, rather than requiring an app context for configuration.
flask.api.index#flask.json.dumps
ENV What environment the app is running in. Flask and extensions may enable behaviors based on the environment, such as enabling debug mode. The env attribute maps to this 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' Changelog New in version 1.0.
flask.config.index#ENV
flask.escape() Replace the characters &, <, >, ', and " in the string with HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. If the object has an __html__ method, it is called and the return value is assumed to already be safe for HTML. Parameters s – An object to be converted to a string and escaped. Returns A Markup string with the escaped text.
flask.api.index#flask.escape
EXPLAIN_TEMPLATE_LOADING Log debugging information tracing how a template file was loaded. This can be useful to figure out why a template was not loaded or the wrong file appears to be loaded. Default: False
flask.config.index#EXPLAIN_TEMPLATE_LOADING
Extensions Extensions are extra packages that add functionality to a Flask application. For example, an extension might add support for sending email or connecting to a database. Some extensions add entire new frameworks to help build certain types of applications, like a REST API. Finding Extensions Flask extensions are usually named “Flask-Foo” or “Foo-Flask”. You can search PyPI for packages tagged with Framework :: Flask. Using Extensions Consult each extension’s documentation for installation, configuration, and usage instructions. Generally, extensions pull their own configuration from app.config and are passed an application instance during initialization. For example, an extension called “Flask-Foo” might be used like this: from flask_foo import Foo foo = Foo() app = Flask(__name__) app.config.update( FOO_BAR='baz', FOO_SPAM='eggs', ) foo.init_app(app) Building Extensions While the PyPI contains many Flask extensions, you may not find an extension that fits your need. If this is the case, you can create your own. Read Flask Extension Development to develop your own Flask extension.
flask.extensions.index
FastCGI FastCGI is a deployment option on servers like nginx, lighttpd, and cherokee; see uWSGI and Standalone WSGI Containers for other options. To use your WSGI application with any of them you will need a FastCGI server first. The most popular one is flup which we will use for this guide. Make sure to have it installed to follow along. Watch Out Please make sure in advance that any app.run() calls you might have in your application file are inside an if __name__ == '__main__': block or moved to a separate file. Just make sure it’s not called because this will always start a local WSGI server which we do not want if we deploy that application to FastCGI. Creating a .fcgi file First you need to create the FastCGI server file. Let’s call it yourapplication.fcgi: #!/usr/bin/python from flup.server.fcgi import WSGIServer from yourapplication import app if __name__ == '__main__': WSGIServer(app).run() This is enough for Apache to work, however nginx and older versions of lighttpd need a socket to be explicitly passed to communicate with the FastCGI server. For that to work you need to pass the path to the socket to the WSGIServer: WSGIServer(application, bindAddress='/path/to/fcgi.sock').run() The path has to be the exact same path you define in the server config. Save the yourapplication.fcgi file somewhere you will find it again. It makes sense to have that in /var/www/yourapplication or something similar. Make sure to set the executable bit on that file so that the servers can execute it: $ chmod +x /var/www/yourapplication/yourapplication.fcgi Configuring Apache The example above is good enough for a basic Apache deployment but your .fcgi file will appear in your application URL e.g. example.com/yourapplication.fcgi/news/. There are few ways to configure your application so that yourapplication.fcgi does not appear in the URL. A preferable way is to use the ScriptAlias and SetHandler configuration directives to route requests to the FastCGI server. The following example uses FastCgiServer to start 5 instances of the application which will handle all incoming requests: LoadModule fastcgi_module /usr/lib64/httpd/modules/mod_fastcgi.so FastCgiServer /var/www/html/yourapplication/app.fcgi -idle-timeout 300 -processes 5 <VirtualHost *> ServerName webapp1.mydomain.com DocumentRoot /var/www/html/yourapplication AddHandler fastcgi-script fcgi ScriptAlias / /var/www/html/yourapplication/app.fcgi/ <Location /> SetHandler fastcgi-script </Location> </VirtualHost> These processes will be managed by Apache. If you’re using a standalone FastCGI server, you can use the FastCgiExternalServer directive instead. Note that in the following the path is not real, it’s simply used as an identifier to other directives such as AliasMatch: FastCgiServer /var/www/html/yourapplication -host 127.0.0.1:3000 If you cannot set ScriptAlias, for example on a shared web host, you can use WSGI middleware to remove yourapplication.fcgi from the URLs. Set .htaccess: <IfModule mod_fcgid.c> AddHandler fcgid-script .fcgi <Files ~ (\.fcgi)> SetHandler fcgid-script Options +FollowSymLinks +ExecCGI </Files> </IfModule> <IfModule mod_rewrite.c> Options +FollowSymlinks RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ yourapplication.fcgi/$1 [QSA,L] </IfModule> Set yourapplication.fcgi: #!/usr/bin/python #: optional path to your local python site-packages folder import sys sys.path.insert(0, '<your_local_path>/lib/python<your_python_version>/site-packages') from flup.server.fcgi import WSGIServer from yourapplication import app class ScriptNameStripper(object): def __init__(self, app): self.app = app def __call__(self, environ, start_response): environ['SCRIPT_NAME'] = '' return self.app(environ, start_response) app = ScriptNameStripper(app) if __name__ == '__main__': WSGIServer(app).run() Configuring lighttpd A basic FastCGI configuration for lighttpd looks like that: fastcgi.server = ("/yourapplication.fcgi" => (( "socket" => "/tmp/yourapplication-fcgi.sock", "bin-path" => "/var/www/yourapplication/yourapplication.fcgi", "check-local" => "disable", "max-procs" => 1 )) ) alias.url = ( "/static/" => "/path/to/your/static/" ) url.rewrite-once = ( "^(/static($|/.*))$" => "$1", "^(/.*)$" => "/yourapplication.fcgi$1" ) Remember to enable the FastCGI, alias and rewrite modules. This configuration binds the application to /yourapplication. If you want the application to work in the URL root you have to work around a lighttpd bug with the LighttpdCGIRootFix middleware. Make sure to apply it only if you are mounting the application the URL root. Also, see the Lighty docs for more information on FastCGI and Python (note that explicitly passing a socket to run() is no longer necessary). Configuring nginx Installing FastCGI applications on nginx is a bit different because by default no FastCGI parameters are forwarded. A basic Flask FastCGI configuration for nginx looks like this: location = /yourapplication { rewrite ^ /yourapplication/ last; } location /yourapplication { try_files $uri @yourapplication; } location @yourapplication { include fastcgi_params; fastcgi_split_path_info ^(/yourapplication)(.*)$; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param SCRIPT_NAME $fastcgi_script_name; fastcgi_pass unix:/tmp/yourapplication-fcgi.sock; } This configuration binds the application to /yourapplication. If you want to have it in the URL root it’s a bit simpler because you don’t have to figure out how to calculate PATH_INFO and SCRIPT_NAME: location / { try_files $uri @yourapplication; } location @yourapplication { include fastcgi_params; fastcgi_param PATH_INFO $fastcgi_script_name; fastcgi_param SCRIPT_NAME ""; fastcgi_pass unix:/tmp/yourapplication-fcgi.sock; } Running FastCGI Processes Since nginx and others do not load FastCGI apps, you have to do it by yourself. Supervisor can manage FastCGI processes. You can look around for other FastCGI process managers or write a script to run your .fcgi file at boot, e.g. using a SysV init.d script. For a temporary solution, you can always run the .fcgi script inside GNU screen. See man screen for details, and note that this is a manual solution which does not persist across system restart: $ screen $ /var/www/yourapplication/yourapplication.fcgi Debugging FastCGI deployments tend to be hard to debug on most web servers. Very often the only thing the server log tells you is something along the lines of “premature end of headers”. In order to debug the application the only thing that can really give you ideas why it breaks is switching to the correct user and executing the application by hand. This example assumes your application is called application.fcgi and that your web server user is www-data: $ su www-data $ cd /var/www/yourapplication $ python application.fcgi Traceback (most recent call last): File "yourapplication.fcgi", line 4, in <module> ImportError: No module named yourapplication In this case the error seems to be “yourapplication” not being on the python path. Common problems are: Relative paths being used. Don’t rely on the current working directory. The code depending on environment variables that are not set by the web server. Different python interpreters being used.
flask.deploying.fastcgi.index
flask.flash(message, category='message') Flashes a message to the next request. In order to remove the flashed message from the session and to display it to the user, the template has to call get_flashed_messages(). Changelog Changed in version 0.3: category parameter added. Parameters message (str) – the message to be flashed. category (str) – the category for the message. The following values are recommended: 'message' for any kind of message, 'error' for errors, 'info' for information messages and 'warning' for warnings. However any kind of string can be used as category. Return type None
flask.api.index#flask.flash
class flask.Flask(import_name, static_url_path=None, static_folder='static', static_host=None, host_matching=False, subdomain_matching=False, template_folder='templates', instance_path=None, instance_relative_config=False, root_path=None) The flask object implements a WSGI application and acts as the central object. It is passed the name of the module or package of the application. Once it is created it will act as a central registry for the view functions, the URL rules, template configuration and much more. The name of the package is used to resolve resources from inside the package or the folder the module is contained in depending on if the package parameter resolves to an actual python package (a folder with an __init__.py file inside) or a standard module (just a .py file). For more information about resource loading, see open_resource(). Usually you create a Flask instance in your main module or in the __init__.py file of your package like this: from flask import Flask app = Flask(__name__) About the First Parameter The idea of the first parameter is to give Flask an idea of what belongs to your application. This name is used to find resources on the filesystem, can be used by extensions to improve debugging information and a lot more. So it’s important what you provide there. If you are using a single module, __name__ is always the correct value. If you however are using a package, it’s usually recommended to hardcode the name of your package there. For example if your application is defined in yourapplication/app.py you should create it with one of the two versions below: app = Flask('yourapplication') app = Flask(__name__.split('.')[0]) Why is that? The application will work even with __name__, thanks to how resources are looked up. However it will make debugging more painful. Certain extensions can make assumptions based on the import name of your application. For example the Flask-SQLAlchemy extension will look for the code in your application that triggered an SQL query in debug mode. If the import name is not properly set up, that debugging information is lost. (For example it would only pick up SQL queries in yourapplication.app and not yourapplication.views.frontend) Changelog New in version 1.0: The host_matching and static_host parameters were added. New in version 1.0: The subdomain_matching parameter was added. Subdomain matching needs to be enabled manually now. Setting SERVER_NAME does not implicitly enable it. New in version 0.11: The root_path parameter was added. New in version 0.8: The instance_path and instance_relative_config parameters were added. New in version 0.7: The static_url_path, static_folder, and template_folder parameters were added. Parameters import_name (str) – the name of the application package static_url_path (Optional[str]) – 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 (Optional[str]) – The folder with static files that is served at static_url_path. Relative to the application root_path or an absolute path. Defaults to 'static'. static_host (Optional[str]) – the host to use when adding the static route. Defaults to None. Required when using host_matching=True with a static_folder configured. host_matching (bool) – set url_map.host_matching attribute. Defaults to False. subdomain_matching (bool) – consider the subdomain relative to SERVER_NAME when matching routes. Defaults to False. template_folder (Optional[str]) – 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 (Optional[str]) – 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 (bool) – if set to True relative filenames for loading the config are assumed to be relative to the instance path instead of the application root. root_path (Optional[str]) – 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, name=None) Register a custom template filter. Works exactly like the template_filter() decorator. Parameters name (Optional[str]) – the optional name of the filter, otherwise the function name will be used. f (Callable[[Any], str]) – Return type None add_template_global(f, name=None) Register a custom template global function. Works exactly like the template_global() decorator. Changelog New in version 0.10. Parameters name (Optional[str]) – the optional name of the global function, otherwise the function name will be used. f (Callable[[], Any]) – Return type None add_template_test(f, name=None) Register a custom template test. Works exactly like the template_test() decorator. Changelog New in version 0.10. Parameters name (Optional[str]) – the optional name of the test, otherwise the function name will be used. f (Callable[[Any], bool]) – Return type None add_url_rule(rule, endpoint=None, view_func=None, provide_automatic_options=None, **options) Register a rule for routing incoming requests and building URLs. The route() decorator is a shortcut to call this with the view_func argument. These are equivalent: @app.route("/") def index(): ... def index(): ... app.add_url_rule("/", view_func=index) 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. An error will be raised if a function has already been registered for the endpoint. The methods parameter defaults to ["GET"]. HEAD is always added automatically, and OPTIONS is added automatically by default. view_func does 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 the endpoint() decorator. app.add_url_rule("/", endpoint="index") @app.endpoint("index") def index(): ... If view_func has a required_methods attribute, those methods are added to the passed and automatic methods. If it has a provide_automatic_methods attribute, it is used as the default if the parameter is not passed. Parameters rule (str) – The URL rule string. endpoint (Optional[str]) – The endpoint name to associate with the rule and view function. Used when routing and building URLs. Defaults to view_func.__name__. view_func (Optional[Callable]) – The view function to associate with the endpoint name. provide_automatic_options (Optional[bool]) – Add the OPTIONS method and respond to OPTIONS requests automatically. options (Any) – Extra options passed to the Rule object. Return type None after_request(f) Register a function to run after each request to this object. The function is called with the response object, and must return a response object. This allows the functions to modify or replace the response before it is sent. If a function raises an exception, any remaining after_request functions will not be called. Therefore, this should not be used for actions that must execute, such as to close resources. Use teardown_request() for that. Parameters f (Callable[[Response], Response]) – Return type Callable[[Response], Response] after_request_funcs: t.Dict[AppOrBlueprintKey, t.List[AfterRequestCallable]] A data structure of functions to call at the end of each request, 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 after_request() decorator. This data structure is internal. It should not be modified directly and its format may change at any time. app_context() Create an AppContext. Use as a with block to push the context, which will make current_app point 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 The Application Context. Changelog New in version 0.9. Return type flask.ctx.AppContext app_ctx_globals_class alias of flask.ctx._AppCtxGlobals async_to_sync(func) 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. Parameters func (Callable[[...], Coroutine]) – Return type Callable[[…], Any] auto_find_instance_path() Tries to locate the instance path if it was not provided to the constructor of the application class. It will basically calculate the path to a folder named instance next to your main file or the package. Changelog New in version 0.8. Return type str before_first_request(f) Registers a function to be run before the first request to this instance of the application. The function will be called without any arguments and its return value is ignored. Changelog New in version 0.8. Parameters f (Callable[[], None]) – Return type Callable[[], None] before_first_request_funcs: t.List[BeforeRequestCallable] 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. Changelog New in version 0.8. before_request(f) Register a function to run before each request. For example, this can be used to open a database connection, or to load the logged in user from the session. @app.before_request def load_user(): if "user_id" in session: g.user = db.session.get(session["user_id"]) The function will be called without any arguments. If it 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. Parameters f (Callable[[], None]) – Return type Callable[[], None] before_request_funcs: t.Dict[AppOrBlueprintKey, t.List[BeforeRequestCallable]] A data structure of functions to call at the beginning of each request, 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 before_request() decorator. This data structure is internal. It should not be modified directly and its format may change at any time. blueprints: t.Dict[str, ‘Blueprint’] 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. Changelog New in version 0.7. cli The Click command group for registering CLI commands for this object. The commands are available from the flask command once the application has been discovered and blueprints have been registered. config The configuration dictionary as Config. This behaves exactly like a regular dictionary but supports additional methods to load a config from files. config_class alias of flask.config.Config context_processor(f) Registers a template context processor function. Parameters f (Callable[[], Dict[str, Any]]) – Return type Callable[[], Dict[str, Any]] create_global_jinja_loader() Creates the loader for the Jinja2 environment. Can be used to override just the loader and keeping the rest unchanged. It’s discouraged to override this function. Instead one should override the jinja_loader() function instead. The global loader dispatches between the loaders of the application and the individual blueprints. Changelog New in version 0.7. Return type flask.templating.DispatchingJinjaLoader create_jinja_environment() Create the Jinja environment based on jinja_options and the various Jinja-related methods of the app. Changing jinja_options after this will have no effect. Also adds Flask-related globals and filters to the environment. Changelog Changed in version 0.11: Environment.auto_reload set in accordance with TEMPLATES_AUTO_RELOAD configuration option. New in version 0.5. Return type flask.templating.Environment create_url_adapter(request) Creates a URL adapter for the given request. The URL adapter is created at a point where the request context is not yet set up so the request is passed explicitly. Changelog Changed in version 1.0: SERVER_NAME no longer implicitly enables subdomain matching. Use subdomain_matching instead. 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. New in version 0.6. Parameters request (Optional[flask.wrappers.Request]) – Return type Optional[werkzeug.routing.MapAdapter] property debug: bool Whether debug mode is enabled. When using flask run to 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 the DEBUG config key. This is enabled when env is 'development' and is overridden by the FLASK_DEBUG environment variable. It may not behave as expected if set in code. Do not enable debug mode when deploying in production. Default: True if env is 'development', or False otherwise. 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. delete(rule, **options) Shortcut for route() with methods=["DELETE"]. New in version 2.0. Parameters rule (str) – options (Any) – Return type Callable dispatch_request() Does the request dispatching. Matches the URL and returns the return value of the view or error handler. This does not have to be a response object. In order to convert the return value to a proper response object, call make_response(). Changelog Changed in version 0.7: This no longer does the exception handling, this code was moved to the new full_dispatch_request(). Return type 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] do_teardown_appcontext(exc=<object object>) 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 the appcontext_tearing_down signal is sent. This is called by AppContext.pop(). Changelog New in version 0.9. Parameters exc (Optional[BaseException]) – Return type None 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. 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 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 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' 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. 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 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. 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 get(rule, **options) Shortcut for route() with methods=["GET"]. New in version 2.0. Parameters rule (str) – options (Any) – Return type Callable 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] property got_first_request: bool This attribute is set to True if the application started handling the first request. Changelog New in version 0.8. 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 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] handle_url_build_error(error, endpoint, values) Handle BuildError on url_for(). Parameters error (Exception) – endpoint (str) – values (dict) – Return type str 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] property has_static_folder: bool True if static_folder is set. Changelog New in version 0.5. 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. 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 instance_path Holds the path to the instance folder. Changelog New in version 0.8. iter_blueprints() Iterates over all blueprints by the order they were registered. Changelog New in version 0.11. Return type ValuesView[Blueprint] property jinja_env: flask.templating.Environment The Jinja environment used to load templates. The environment is created the first time this property is accessed. Changing jinja_options after that will have no effect. jinja_environment alias of flask.templating.Environment property jinja_loader: Optional[jinja2.loaders.FileSystemLoader] The Jinja loader for this object’s templates. By default this is a class jinja2.loaders.FileSystemLoader to template_folder if it is set. Changelog New in version 0.5. 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. json_decoder alias of flask.json.JSONDecoder json_encoder alias of flask.json.JSONEncoder log_exception(exc_info) Logs an exception. This is called by handle_exception() if debugging is disabled and right before the handler is called. The default implementation logs the exception as error on the logger. Changelog New in version 0.8. Parameters exc_info (Union[Tuple[type, BaseException, types.TracebackType], Tuple[None, None, None]]) – Return type None property logger: logging.Logger A standard Python Logger for the app, with the same name as name. In debug mode, the logger’s level will be set to DEBUG. If there are no handlers configured, a default handler will be added. See Logging for more information. Changelog Changed in version 1.1.0: The logger takes the same name as name rather 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 check app.debug each time. Only one format is used, not different ones depending on app.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=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 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 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. 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 property name: str The name of the application. This is usually the import name with the difference that it’s guessed from the run file if the import name is main. This name is used as a display name when Flask needs the name of the application. It can be set and overridden to change the value. Changelog New in version 0.8. 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 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 patch(rule, **options) Shortcut for route() with methods=["PATCH"]. New in version 2.0. Parameters rule (str) – options (Any) – Return type Callable 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) post(rule, **options) Shortcut for route() with methods=["POST"]. New in version 2.0. Parameters rule (str) – options (Any) – Return type Callable 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]] property preserve_context_on_exception: bool Returns the value of the PRESERVE_CONTEXT_ON_EXCEPTION configuration value in case it’s set, otherwise a sensible default is returned. Changelog New in version 0.7. process_response(response) Can be overridden in order to modify the response object before it’s sent to the WSGI server. By default this will call all the after_request() decorated functions. 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 property propagate_exceptions: bool Returns the value of the PROPAGATE_EXCEPTIONS configuration value in case it’s set, otherwise a sensible default is returned. Changelog New in version 0.7. put(rule, **options) Shortcut for route() with methods=["PUT"]. New in version 2.0. Parameters rule (str) – options (Any) – Return type Callable 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. 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 request_class alias of flask.wrappers.Request 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 response_class alias of flask.wrappers.Response root_path Absolute path to the package on the filesystem. Used to look up resources contained in the package. 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 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. secret_key If a secret key is set, cryptographic components can use this to sign cookies and other things. Set this to a complex random value when you want to use the secure cookie for instance. This attribute can also be configured from the config with the SECRET_KEY configuration key. Defaults to None. select_jinja_autoescape(filename) Returns True if autoescaping should be active for the given template name. If no template name is given, returns True. Changelog New in version 0.5. Parameters filename (str) – Return type bool 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. 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 session_cookie_name The secure cookie uses this for the name of the session cookie. This attribute can also be configured from the config with the SESSION_COOKIE_NAME configuration key. Defaults to 'session' session_interface = <flask.sessions.SecureCookieSessionInterface object> the session interface to use. By default an instance of SecureCookieSessionInterface is used here. Changelog New in version 0.8. shell_context_processor(f) Registers a shell context processor function. Changelog New in version 0.11. Parameters f (Callable) – Return type Callable 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. 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 property static_folder: Optional[str] The absolute path to the configured static folder. None if no static folder is set. property static_url_path: Optional[str] The URL prefix that the static route will be accessible from. If it was not configured during init, it is derived from static_folder. teardown_appcontext(f) Registers a function to be called when the application context ends. These functions are typically also called when the request context is popped. Example: ctx = app.app_context() ctx.push() ... ctx.pop() When ctx.pop() is executed in the above example, the teardown functions are called just before the app context moves from the stack of active contexts. This becomes relevant if you are using such constructs in tests. Since a request context typically also manages an application context it would also be called when you pop a request context. When a teardown function was called because of an 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] 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. 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] 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. 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. 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 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. 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 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 property templates_auto_reload: bool 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. Changelog New in version 1.0: This property was added but the underlying config and behavior already existed. 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 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. 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 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. 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 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. 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 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 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. 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. 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] 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 url_map_class alias of werkzeug.routing.Map url_rule_class alias of werkzeug.routing.Rule 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] 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. 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. 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. 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
add_template_filter(f, name=None) Register a custom template filter. Works exactly like the template_filter() decorator. Parameters name (Optional[str]) – the optional name of the filter, otherwise the function name will be used. f (Callable[[Any], str]) – Return type None
flask.api.index#flask.Flask.add_template_filter
add_template_global(f, name=None) Register a custom template global function. Works exactly like the template_global() decorator. Changelog New in version 0.10. Parameters name (Optional[str]) – the optional name of the global function, otherwise the function name will be used. f (Callable[[], Any]) – Return type None
flask.api.index#flask.Flask.add_template_global
add_template_test(f, name=None) Register a custom template test. Works exactly like the template_test() decorator. Changelog New in version 0.10. Parameters name (Optional[str]) – the optional name of the test, otherwise the function name will be used. f (Callable[[Any], bool]) – Return type None
flask.api.index#flask.Flask.add_template_test
add_url_rule(rule, endpoint=None, view_func=None, provide_automatic_options=None, **options) Register a rule for routing incoming requests and building URLs. The route() decorator is a shortcut to call this with the view_func argument. These are equivalent: @app.route("/") def index(): ... def index(): ... app.add_url_rule("/", view_func=index) 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. An error will be raised if a function has already been registered for the endpoint. The methods parameter defaults to ["GET"]. HEAD is always added automatically, and OPTIONS is added automatically by default. view_func does 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 the endpoint() decorator. app.add_url_rule("/", endpoint="index") @app.endpoint("index") def index(): ... If view_func has a required_methods attribute, those methods are added to the passed and automatic methods. If it has a provide_automatic_methods attribute, it is used as the default if the parameter is not passed. Parameters rule (str) – The URL rule string. endpoint (Optional[str]) – The endpoint name to associate with the rule and view function. Used when routing and building URLs. Defaults to view_func.__name__. view_func (Optional[Callable]) – The view function to associate with the endpoint name. provide_automatic_options (Optional[bool]) – Add the OPTIONS method and respond to OPTIONS requests automatically. options (Any) – Extra options passed to the Rule object. Return type None
flask.api.index#flask.Flask.add_url_rule
after_request(f) Register a function to run after each request to this object. The function is called with the response object, and must return a response object. This allows the functions to modify or replace the response before it is sent. If a function raises an exception, any remaining after_request functions will not be called. Therefore, this should not be used for actions that must execute, such as to close resources. Use teardown_request() for that. Parameters f (Callable[[Response], Response]) – Return type Callable[[Response], Response]
flask.api.index#flask.Flask.after_request
after_request_funcs: t.Dict[AppOrBlueprintKey, t.List[AfterRequestCallable]] A data structure of functions to call at the end of each request, 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 after_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.after_request_funcs
flask.appcontext_popped This signal is sent when an application context is popped. The sender is the application. This usually falls in line with the appcontext_tearing_down signal. Changelog New in version 0.10.
flask.api.index#flask.appcontext_popped
flask.appcontext_pushed This signal is sent when an application context is pushed. The sender is the application. This is usually useful for unittests in order to temporarily hook in information. For instance it can be used to set a resource early onto the g object. Example usage: from contextlib import contextmanager from flask import appcontext_pushed @contextmanager def user_set(app, user): def handler(sender, **kwargs): g.user = user with appcontext_pushed.connected_to(handler, app): yield And in the testcode: def test_user_me(self): with user_set(app, 'john'): c = app.test_client() resp = c.get('/users/me') assert resp.data == 'username=john' Changelog New in version 0.10.
flask.api.index#flask.appcontext_pushed
flask.appcontext_tearing_down This signal is sent when the app context 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 appcontext_tearing_down appcontext_tearing_down.connect(close_db_connection, app) 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.appcontext_tearing_down
app_context() Create an AppContext. Use as a with block to push the context, which will make current_app point 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 The Application Context. Changelog New in version 0.9. Return type flask.ctx.AppContext
flask.api.index#flask.Flask.app_context
app_ctx_globals_class alias of flask.ctx._AppCtxGlobals
flask.api.index#flask.Flask.app_ctx_globals_class
async_to_sync(func) 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. Parameters func (Callable[[...], Coroutine]) – Return type Callable[[…], Any]
flask.api.index#flask.Flask.async_to_sync
auto_find_instance_path() Tries to locate the instance path if it was not provided to the constructor of the application class. It will basically calculate the path to a folder named instance next to your main file or the package. Changelog New in version 0.8. Return type str
flask.api.index#flask.Flask.auto_find_instance_path
before_first_request(f) Registers a function to be run before the first request to this instance of the application. The function will be called without any arguments and its return value is ignored. Changelog New in version 0.8. Parameters f (Callable[[], None]) – Return type Callable[[], None]
flask.api.index#flask.Flask.before_first_request
before_first_request_funcs: t.List[BeforeRequestCallable] 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. Changelog New in version 0.8.
flask.api.index#flask.Flask.before_first_request_funcs
before_request(f) Register a function to run before each request. For example, this can be used to open a database connection, or to load the logged in user from the session. @app.before_request def load_user(): if "user_id" in session: g.user = db.session.get(session["user_id"]) The function will be called without any arguments. If it 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. Parameters f (Callable[[], None]) – Return type Callable[[], None]
flask.api.index#flask.Flask.before_request
before_request_funcs: t.Dict[AppOrBlueprintKey, t.List[BeforeRequestCallable]] A data structure of functions to call at the beginning of each request, 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 before_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.before_request_funcs
blueprints: t.Dict[str, ‘Blueprint’] 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. Changelog New in version 0.7.
flask.api.index#flask.Flask.blueprints
cli The Click command group for registering CLI commands for this object. The commands are available from the flask command once the application has been discovered and blueprints have been registered.
flask.api.index#flask.Flask.cli
flask.cli.run_command = <Command run> Run a local development server. This server is for development purposes only. It does not provide the stability, security, or performance of production WSGI servers. The reloader and debugger are enabled by default if FLASK_ENV=development or FLASK_DEBUG=1. Parameters args (Any) – kwargs (Any) – Return type Any
flask.api.index#flask.cli.run_command
flask.cli.shell_command = <Command shell> Run an interactive Python shell in the context of a given Flask application. The application will populate the default namespace of this shell according to its configuration. This is useful for executing small snippets of management code without having to manually configure the application. Parameters args (Any) – kwargs (Any) – Return type Any
flask.api.index#flask.cli.shell_command
config The configuration dictionary as Config. This behaves exactly like a regular dictionary but supports additional methods to load a config from files.
flask.api.index#flask.Flask.config
config_class alias of flask.config.Config
flask.api.index#flask.Flask.config_class
context_processor(f) Registers a template context processor function. Parameters f (Callable[[], Dict[str, Any]]) – Return type Callable[[], Dict[str, Any]]
flask.api.index#flask.Flask.context_processor
create_global_jinja_loader() Creates the loader for the Jinja2 environment. Can be used to override just the loader and keeping the rest unchanged. It’s discouraged to override this function. Instead one should override the jinja_loader() function instead. The global loader dispatches between the loaders of the application and the individual blueprints. Changelog New in version 0.7. Return type flask.templating.DispatchingJinjaLoader
flask.api.index#flask.Flask.create_global_jinja_loader
create_jinja_environment() Create the Jinja environment based on jinja_options and the various Jinja-related methods of the app. Changing jinja_options after this will have no effect. Also adds Flask-related globals and filters to the environment. Changelog Changed in version 0.11: Environment.auto_reload set in accordance with TEMPLATES_AUTO_RELOAD configuration option. New in version 0.5. Return type flask.templating.Environment
flask.api.index#flask.Flask.create_jinja_environment
create_url_adapter(request) Creates a URL adapter for the given request. The URL adapter is created at a point where the request context is not yet set up so the request is passed explicitly. Changelog Changed in version 1.0: SERVER_NAME no longer implicitly enables subdomain matching. Use subdomain_matching instead. 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. New in version 0.6. Parameters request (Optional[flask.wrappers.Request]) – Return type Optional[werkzeug.routing.MapAdapter]
flask.api.index#flask.Flask.create_url_adapter
flask.current_app A proxy to the application handling the current request. This is useful to access the application without needing to import it, or if it can’t be imported, such as when using the application factory pattern or in blueprints and extensions. This is only available when an application context is pushed. This happens automatically during requests and CLI commands. It can be controlled manually with app_context(). This is a proxy. See Notes On Proxies for more information.
flask.api.index#flask.current_app
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.
flask.api.index#flask.Flask.default_config
delete(rule, **options) Shortcut for route() with methods=["DELETE"]. New in version 2.0. Parameters rule (str) – options (Any) – Return type Callable
flask.api.index#flask.Flask.delete
dispatch_request() Does the request dispatching. Matches the URL and returns the return value of the view or error handler. This does not have to be a response object. In order to convert the return value to a proper response object, call make_response(). Changelog Changed in version 0.7: This no longer does the exception handling, this code was moved to the new full_dispatch_request(). Return type 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.dispatch_request
do_teardown_appcontext(exc=<object object>) 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 the appcontext_tearing_down signal is sent. This is called by AppContext.pop(). Changelog New in version 0.9. Parameters exc (Optional[BaseException]) – Return type None
flask.api.index#flask.Flask.do_teardown_appcontext