Flask Application Object API
The Flask class is the core of the entire framework. It runs as a WSGI application and centrally manages all features such as routing, templates, configuration, hooks, and more.
Creation method:
app = Flask(__name__)
Constructor parameters
The following are all the parameters that can be passed when creating a Flask instance:
| Parameter | Type | Default value | Description |
|---|---|---|---|
| import_name | str | Required | Application module/package name. Flask uses it to locate templates and static files. Passed as a single file.__name__, pass the package name |
| static_url_path | str | None | The URL path exposed for static files. If not set, uses the folder name of static_folder, e.g., /static. |
| static_folder | str | "static" | The folder path for static files (CSS, JS, images), relative to root_path or an absolute path. |
| static_host | str | None | The hostname for the static file route. Only needed 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 folder path for Jinja2 template files. |
| instance_path | str | None (auto-discovery) | The instance folder path, used to store files that are not committed to version control at runtime. 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 root path, usually auto-detected. Only namespace packages need to set it manually. |
Core attributes
| Property | Type | Description |
|---|---|---|
| name | str | The application name. If import_name is __main__, the main module file name is used. |
| config | Config | Configuration dictionary object, storing all configuration items |
| debug | bool | Whether debug mode is enabled. Equivalent to config["DEBUG"]. |
| testing | bool | Whether testing mode is enabled. Equivalent to config["TESTING"]. |
| secret_key | str | Secret key used for Session signing. Equivalent to config["SECRET_KEY"] |
| permanent_session_lifetime | timedelta | The lifetime of permanent sessions, default 31 days. |
| url_map | Map | The Werkzeug URL map, storing all routing rules. |
| view_functions | dict | Mapping dictionary of endpoint → view function. |
| blueprints | dict | Registered blueprint name → Blueprint instance mapping |
| extensions | dict | Extension storage dictionary. Extensions store their own state by module name. |
| logger | Logger | Python standard logging.Logger, with the app name as the logger name |
| jinja_env | Environment | Jinja2 environment instance, controlling how templates are loaded |
| json | JSONProvider | JSON handler provider instance, replaceable with a custom JSON library |
| aborter | Aborter | HTTP exception raiser, called by the abort() function. |
| cli | AppGroup | Click command group for adding custom CLI commands. |
| instance_path | str | Absolute path to the instance folder. |
| root_path | str | 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 | Class used to create request objects |
| response_class | Response | Class used to create response objects |
| session_interface | SecureCookieSessionInterface() | Session backend interface, replaceable with Redis/database sessions |
| jinja_environment | Environment | Jinja2 environment class |
| app_ctx_globals_class | _AppCtxGlobals | Class of the g object |
| config_class | Config | Class of the configuration object |
| aborter_class | Aborter | Class of the exception thrower |
| json_provider_class | DefaultJSONProvider | Class of the JSON handler |
| url_rule_class | Rule | Class for URL rules (Werkzeug) |
| url_map_class | Map | URL map class (Werkzeug) |
| test_client_class | None (default FlaskClient) | Test client class |
| test_cli_runner_class | None (default FlaskCliRunner) | CLI test runner class |
| jinja_options | {} | Extra options passed to the Jinja2 environment. |
URL routing method
| Methods | Signature | Description |
|---|---|---|
| route | (rule, **options) | Decorator that binds a URL rule to a view function. |
| get | (rule, **options) | Decorator that only binds the GET method (equivalent to methods=["GET"]) |
| post | (rule, **options) | Decorator that binds only the POST method. |
| put | (rule, **options) | Decorator that only binds the PUT method |
| delete | (rule, **options) | Decorator that binds only the DELETE method. |
| patch | (rule, **options) | Decorator that binds only the PATCH method. |
| add_url_rule | (rule, endpoint, view_func, provide_automatic_options, **options) | Adds URL rules programmatically. The route decorator calls this method under the hood. |
| url_for | (endpoint, *, _anchor, _method, _scheme, _external, **values) | Generates a URL from an endpoint and parameters. In blueprints, the endpoint must be prefixed with the blueprint name. |
| register_blueprint | (blueprint, **options) | Register a blueprint, with override parameters such as url_prefix, subdomain, etc. |
| iter_blueprints | () | Iterate over all blueprints in registration order |
Options supported by the route decorator include:methods(HTTP method list),endpoint(custom endpoint name),defaults(default parameters),subdomain(subdomain), etc.
Request lifecycle hooks (decorators)
The following methods can all be used as decorators to insert custom logic at different stages of the request:
| Methods | Execution timing | Behavior when returning non-None | Typical use |
|---|---|---|---|
| before_request | Before route dispatching | Return value used as the final response, skipping the view function. | Login checks, permission verification |
| after_request | After the response is constructed, before it is sent | Must accept and return a Response object. | Add security headers, CORS headers |
| teardown_request | When the request context is popped | Return value is ignored | Release request-level resources |
| teardown_appcontext | When the app context is popped | Return value is ignored | Close 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. | Return value is ignored | Preprocess URL parameters |
| url_defaults | When building URLs with url_for | Modifies the passed-in values dictionary. | Adds default parameters to url_for. |
| template_filter | — (registration nature) | — | Register Jinja2 template filter |
| template_test | — (registration nature) | — | Register Jinja2 template test |
| template_global | — (registration nature) | — | Register 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 method
The following methods are called internally during request handling and can be overridden in subclasses:
| Methods | 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 view function's return value into a Response object. |
| finalize_request(ctx, rv) | Finalization: calls make_response and after_request hooks |
| process_response(ctx, response) | Post-response processing: executes after_request functions and session saving |
| full_dispatch_request(ctx) | Full request dispatch entry point: preprocess → dispatch → finalize |
| handle_http_exception(ctx, e) | Handles HTTP exceptions, looks up the corresponding errorhandler |
| handle_user_exception(ctx, e) | Handles exceptions from user code, distinguishing between HTTP exceptions and normal exceptions. |
| handle_exception(ctx, e) | Final exception handling, returns a 500 response. |
| ensure_sync(func) | Ensures the function executes synchronously. Async functions are wrapped to be synchronous. |
| make_default_options_response(ctx) | Generates automatic OPTIONS responses. |
| raise_routing_exception(request) | Handles routing exceptions (e.g., trailing slash redirects). |
Templates and static files
| Methods | Description |
|---|---|
| create_jinja_environment() | Creates and configures the Jinja2 environment. Automatically called on first access to jinja_env. |
| create_global_jinja_loader() | Creates the global Jinja2 loader, supporting template dispatch between the app and blueprints. |
| select_jinja_autoescape(filename) | Determines whether a given file requires automatic escaping. Returns True by default for .html/.htm/.xml/.xhtml/.svg |
| update_template_context(ctx, context) | Injects built-in variables such as request, session, g, config into the template context |
| send_static_file(filename) | Send files from static_folder, automatically registered as /static/ |
| get_send_file_max_age(filename) | Gets the cache time for static files. Defaults to the SEND_FILE_MAX_AGE_DEFAULT config. |
| open_resource(resource, mode="rb") | Opens resource files under root_path in binary mode. |
| open_instance_resource(resource, mode="rb") | Opens resource files under instance_path, supporting write mode. |
Context management
| Methods | Description |
|---|---|
| app_context() | Creates the app context, manually pushed with a with statement. Makes current_app and g available. |
| request_context(environ) | Creates the request context from the WSGI environ. |
| test_request_context(*args, **kwargs) | Creates a mock request context for testing. Accepts path, method, data, json and other parameters. |
| wsgi_app(environ, start_response) | Core WSGI application method. Can wrap middleware via app.wsgi_app = Middleware(app.wsgi_app) |
Testing and development tools
| Methods | Description |
|---|---|
| test_client(use_cookies=True, **kwargs) | Create a test client to simulate browser requests. Returns a FlaskClient instance |
| test_cli_runner(**kwargs) | Create a CLI test runner for testing custom commands. Returns a FlaskCliRunner instance |
| run(host, port, debug, load_dotenv, **options) | Starts the development server. Use Gunicorn/Waitress in production. |
| make_shell_context() | Build the context dictionary for the flask shell. Run all shell_context_processor |
| log_exception(ctx, exc_info) | Logs exceptions to the logger, passing in the exc_info tuple |
Utility methods
| Methods | Description |
|---|---|
| redirect(location, code=303) | Create a redirect response object |
| async_to_sync(func) | Convert async coroutine functions to synchronous functions |
| create_url_adapter(request) | Creates a URL adapter from the request or config, used for URL building. |
| inject_url_defaults(endpoint, values) | Injects default parameters into the URL building process. |
| handle_url_build_error(error, endpoint, values) | Handles url_for build failures and can return a fallback URL. |
| make_config(instance_relative) | Create a Config instance, which can be overridden by subclasses to customize configuration |
| make_aborter() | Create an Aborter instance |
| trap_http_exception(e) | Determines whether to raise HTTP exceptions as normal exceptions. |
| auto_find_instance_path() | Automatically finds the instance folder path. |
Code Examples
Example
from flask import Flask
# Create the app, specify template and static folders
app = Flask(__name__,
template_folder="templates",
static_folder="static",
instance_relative_config=True)
# Set the secret key
app.secret_key = "your-secret-key"
# Register routes
@app.route("/")
def index():
return "<h1>Hello, EXAMPLE!</h1>"
# Register before_request hook
@app.before_request
def check_auth():
# Check user authentication status here
pass
# Register after_request hook
@app.after_request
def add_header(response):
# Add custom headers to each response
response.headers["X-Custom-Header"] = "EXAMPLE"
return response
# Register error handlers
@app.errorhandler(404)
def not_found(error):
return "<h1>Page not found</h1>", 404
# Register custom CLI command
@app.cli.command("hello")
def hello_command():
"""Print greeting"""
print("Hello from EXAMPLE Flask App!")
# Create the app, specify template and static folders
app = Flask(__name__,
template_folder="templates",
static_folder="static",
instance_relative_config=True)
# Set the secret key
app.secret_key = "your-secret-key"
# Register routes
@app.route("/")
def index():
return "<h1>Hello, EXAMPLE!</h1>"
# Register before_request hook
@app.before_request
def check_auth():
# Check user authentication status here
pass
# Register after_request hook
@app.after_request
def add_header(response):
# Add custom headers to each response
response.headers["X-Custom-Header"] = "EXAMPLE"
return response
# Register error handlers
@app.errorhandler(404)
def not_found(error):
return "<h1>Page not found</h1>", 404
# Register custom CLI command
@app.cli.command("hello")
def hello_command():
"""Print greeting"""
print("Hello from EXAMPLE Flask App!")