Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Flask Application Object API

Flask Application Object API

The Flask class is the core of the entire framework. It runs as a WSGI application and centrally manages all functionality such as routing, templates, configuration, and hooks.

Creation:

app = Flask(__name__)


Constructor Parameters

The following are all the parameters that can be passed when creating a Flask instance:

Parameters Type Default value Description
import_name str Required Application module/package name, which Flask uses to locate templates and static files. For a single file, pass namethe module name; for a package, pass the package name
static_url_path str None The URL path at which static files are exposed externally. If not set, the folder name of static_folder is used, such as /static
static_folder str "static" The path to the folder that stores static files (CSS, JS, images), relative to root_path or an absolute path
static_host str None The host name for static file routing, only required when host_matching=True
host_matching bool False Whether to match routes by the Host header
subdomain_matching bool False Whether to enable subdomain route matching
template_folder str "templates" The path to the folder that stores Jinja2 template files
instance_path str None (auto-discovery) The instance folder path, which stores files generated at runtime that are not committed to version control. Set to an absolute path
instance_relative_config bool False When True, relative paths in the configuration file are based on instance_path rather than root_path
root_path str None (auto-discovery) The application's root path, usually inferred automatically; only namespace packages need to set it manually

Core Attributes

property Type Description
name str The application name. If import_name is mainthe main module, the main module's filename is used
config Config The configuration dictionary object, which stores all configuration items
debug bool Whether debug mode is enabled. Equivalent to config["DEBUG"]
testing bool Whether test mode is enabled. Equivalent to config["TESTING"]
secret_key str The secret key used for session signing. Equivalent to config["SECRET_KEY"]
permanent_session_lifetime timedelta The lifetime of permanent sessions, 31 days by default
url_map Map Werkzeug's URL map, which stores all routing rules
view_functions dict A dictionary mapping endpoints → view functions
blueprints dict A mapping of registered blueprint names → Blueprint instances
extensions dict The extensions storage dictionary, where extensions store their own state by module name
logger Logger The Python standard logging.Logger, with the application name as the logger name
jinja_env Environment The Jinja2 environment instance, which controls how templates are loaded
json JSONProvider The JSON provider instance, which can be replaced with a custom JSON library
aborter Aborter The HTTP exception aborter, called by the abort() function
cli AppGroup The Click command group, to which custom CLI commands can be added
instance_path str The absolute path of the instance folder
root_path str The absolute path of the application root directory

Overridable Class Attributes

The following attributes can be overridden in subclasses to customize framework behavior:

property Default value Description
request_class Request The class used to create request objects
response_class Response The class used to create response objects
session_interface SecureCookieSessionInterface() The session backend interface, which can be replaced with a Redis/database session
jinja_environment Environment The Jinja2 environment class
app_ctx_globals_class _AppCtxGlobals The class of the g object
config_class Config The class of the configuration object
aborter_class Aborter The class of the aborter
json_provider_class DefaultJSONProvider The class of the JSON provider
url_rule_class Rule The URL rule class (Werkzeug)
url_map_class Map The URL map class (Werkzeug)
test_client_class None (default FlaskClient) The test client class
test_cli_runner_class None (default FlaskCliRunner) The CLI test runner class
jinja_options {} Additional options passed to the Jinja2 environment

URL Routing Methods

Method Signing Description
route (rule, **options) A decorator that binds a URL rule to a view function
get (rule, **options) A decorator that binds only the GET method (equivalent to methods=["GET"])
post (rule, **options) A decorator that binds only the POST method
put (rule, **options) A decorator that binds only the PUT method
delete (rule, **options) A decorator that binds only the DELETE method
patch (rule, **options) A decorator that binds only the PATCH method
add_url_rule (rule, endpoint, view_func, provide_automatic_options, **options) Adds a URL rule programmatically. The route decorator calls this method internally
url_for (endpoint, *, _anchor, _method, _scheme, _external, **values) Generates a URL from an endpoint and arguments. In blueprints, the endpoint must be prefixed with the blueprint name
register_blueprint (blueprint, **options) Registers a blueprint; override parameters such as url_prefix and subdomain can be specified
iter_blueprints () Iterates over all blueprints in registration order

The options supported by the route decorator include:methods(a list of HTTP methods),endpoint(a custom endpoint name),defaults(default arguments),subdomain(subdomain), and so on.


Request Lifecycle Hooks (Decorators)

All of the following methods can be used as decorators to insert custom logic at different stages of a request.

Method Execution Timing Behavior for non-None returns Typical use
before_request Before route dispatch The return value is used as the final response, skipping the view function Login checks, permission verification
after_request After the response is built, before it is sent Must accept and return a Response object Adding security headers, CORS headers
teardown_request When the request context is popped The return value is ignored Releasing request-level resources
teardown_appcontext When the application context is popped The return value is ignored Closing the Database Connection
errorhandler When a specified status code or exception occurs The return value is used as the response for the error page Custom 404/500 pages
url_value_preprocessor After URL variables are extracted, before the view is called The return value is ignored Preprocessing URL parameters
url_defaults When url_for builds a URL Modifies the passed values dictionary Adds default arguments to url_for
template_filter — (registration) — Registers a Jinja2 template filter
template_test — (registration) — Registers a Jinja2 template test
template_global — (registration) — Registers a Jinja2 global function
shell_context_processor When flask shell starts Returns a dict that is merged into the shell context Pre-imports commonly used objects into flask shell

Request Handling Methods

The following methods are called internally during request processing and can be overridden in subclasses:

Method Description
preprocess_request(ctx) Request preprocessing: executes before_request functions and URL preprocessors
dispatch_request(ctx) Core dispatch: matches the URL and calls the corresponding view function
make_response(rv) Converts the return value of the view function into a Response object
finalize_request(ctx, rv) Finalization: calls make_response and after_request hooks
process_response(ctx, response) Response post-processing: executes after_request functions and session saving
full_dispatch_request(ctx) The complete request dispatch entry point: preprocess → dispatch → finalize
handle_http_exception(ctx, e) Handles HTTP exceptions and finds the corresponding errorhandler
handle_user_exception(ctx, e) Handles exceptions from user code, distinguishing HTTP exceptions from ordinary exceptions
handle_exception(ctx, e) Final exception handling, returning a 500 response
ensure_sync(func) Ensures the function executes synchronously. Async functions are wrapped to be synchronous
make_default_options_response(ctx) Generates an automatic OPTIONS response
raise_routing_exception(request) Handles routing exceptions (such as trailing-slash redirects)

Templates and Static Files

Method Description
create_jinja_environment() Creates and configures the Jinja2 environment. Called automatically on first access to jinja_env
create_global_jinja_loader() Creates the global Jinja2 loader, supporting template dispatch for applications and blueprints
select_jinja_autoescape(filename) Determines whether a given file should be auto-escaped. By default, .html/.htm/.xml/.xhtml/.svg return True
update_template_context(ctx, context) Injects built-in variables such as request, session, g, and config into the template context
send_static_file(filename) Sends files from static_folder, automatically registered as /static/path:filename Routing
get_send_file_max_age(filename) Gets the cache duration for static files, using the SEND_FILE_MAX_AGE_DEFAULT configuration by default
open_resource(resource, mode="rb") Opens a resource file under root_path in binary mode
open_instance_resource(resource, mode="rb") Opens a resource file under instance_path, supporting write mode

Context management

Method Description
app_context() Creates an application context to be pushed manually with a with statement. Makes current_app and g available
request_context(environ) Creates a request context from the WSGI environ
test_request_context(*args, **kwargs) Creates a simulated request context for testing. Accepts parameters such as path, method, data, and json
wsgi_app(environ, start_response) The core WSGI application method. Middleware can be wrapped via app.wsgi_app = Middleware(app.wsgi_app)

Testing and Development Tools

Method Description
test_client(use_cookies=True, **kwargs) Creates a test client that simulates a browser sending requests. Returns a FlaskClient instance
test_cli_runner(**kwargs) Creates a CLI test runner for testing custom commands. Returns a FlaskCliRunner instance
run(host, port, debug, load_dotenv, **options) Starts the development server. Production environments should use Gunicorn/Waitress
make_shell_context() Builds the context dictionary for flask shell. Runs all shell_context_processor functions
log_exception(ctx, exc_info) Logs an exception to the logger, passing an exc_info tuple

Utility Methods

Method Description
redirect(location, code=303) Creates a redirect response object
async_to_sync(func) Converts an async coroutine function into a synchronous function
create_url_adapter(request) Creates a URL adapter from the request or configuration for URL building
inject_url_defaults(endpoint, values) Injects default arguments into the URL building process
handle_url_build_error(error, endpoint, values) Handles cases where url_for fails to build a URL, and can return an alternative URL
make_config(instance_relative) Creates a Config instance; can be overridden in subclasses to customize configuration
make_aborter() Creates an Aborter instance
trap_http_exception(e) Determines whether to raise HTTP exceptions as ordinary exceptions
auto_find_instance_path() Automatically finds the instance folder path

Code Example

Example

from

flask

import

Flask

Creates the application, specifying the template and static folders

app

=

Flask

(

name

,

           template_folder

=

"templates"

,

           static_folder

=

"static"

,

           instance_relative_config

=

True

)

Sets the secret key

app.

secret_key

=

"your-secret-key"

Registration route

@

app.

route

(

"/"

)

def

index

(

)

:

   

return

"

Hello, RUNOOB!

"

Registers a before_request hook

@

app.

before_request

def

check_auth

(

)

:

   

Check user authentication status here

   

pass

Registers an after_request hook

@

app.

after_request

def

add_header

(

response

)

:

   

Adds a custom header to every response

    response.

headers

[

"X-Custom-Header"

]

=

"RUNOOB"

   

return

response

Registers an error handler

@

app.

errorhandler

(

404

)

def

not_found

(

error

)

:

   

return

"

Page not found

"

,

404

Registers a custom CLI command

@

app.

cli

.

command

(

"hello"

)

def

hello_command

(

)

:

   

"""Print a greeting"""

   

print

(

"Hello from RUNOOB Flask App!"

)


Related Documentation