Flask Api Application Object
The Flask class is the core of the entire framework. It runs as a WSGI application and centrally manages all functionalities including routing, templates, configuration, hooks, etc.
Creation method:
app = Flask( __name__ )
* * *
## Constructor Parameters
The following are all parameters that can be passed when creating a Flask instance:
| Parameter | Type | Default | Description |
| --- | --- | --- | --- |
| import_name | str | Required | The application module/package name. Flask uses it to locate templates and static files. Pass __name__ for a single file, or the package name for a package |
| 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 absolute path |
| static_host | str | None | The hostname for static file routing, only needed when host_matching=True |
| host_matching | bool | False | Whether to match routes by Host header |
| subdomain_matching | bool | False | Whether to enable subdomain routing matching |
| template_folder | str | "templates" | The folder path for Jinja2 template files |
| instance_path | str | None (auto-discovered) | The instance folder path, stores files not committed to version control at runtime. Set to absolute path |
| instance_relative_config | bool | False | When True, relative paths in config files are based on instance_path instead of root_path |
| root_path | str | None (auto-discovered) | The root path of the application, usually automatically inferred, only needs manual setting for namespace packages |
* * *
## Core Attributes
| Attribute | Type | Description |
| --- | --- | --- |
| name | str | Application name. If import_name is __main__, takes the main filename |
| config | Config | Configuration dictionary object, stores all configuration items |
| debug | bool | Whether debug mode is enabled. Equivalent to config |
| testing | bool | Whether test mode is enabled. Equivalent to config |
| secret_key | str | Security key, used for Session signing. Equivalent to config |
| permanent_session_lifetime | timedelta | Lifetime of permanent Session, default 31 days |
| url_map | Map | Werkzeug URL mapping table, stores all routing rules |
| view_functions | dict | endpoint β view function mapping dictionary |
| blueprints | dict | Registered blueprint name β Blueprint instance mapping |
| extensions | dict | Extension storage dictionary, extensions store their state by module name |
| logger | Logger | Python standard logging.Logger, application name as logger name |
| jinja_env | Environment | Jinja2 environment instance, controls template loading method |
| json | JSONProvider | JSON processing provider instance, can be replaced with custom JSON library |
| aborter | Aborter | HTTP exception thrower, called by abort() function |
| cli | AppGroup | Click command group, can add custom CLI commands |
| instance_path | str | Absolute path of instance folder |
| root_path | str | Absolute path of application root directory |
* * *
## Overridable Class Attributes
The following attributes can be overridden in subclasses to customize framework behavior:
| Attribute | Default | 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, can be replaced with Redis/Database Session |
| jinja_environment | Environment | Jinja2 environment class |
| app_ctx_globals_class | _AppCtxGlobals | Class for g object |
| config_class | Config | Class for configuration objects |
| aborter_class | Aborter | Class for exception thrower |
| json_provider_class | DefaultJSONProvider | Class for JSON processor |
| url_rule_class | Rule | URL rule class (Werkzeug) |
| url_map_class | Map | URL mapping class (Werkzeug) |
| test_client_class | None (default FlaskClient) | Class for test client |
| test_cli_runner_class | None (default FlaskCliRunner) | Class for CLI test runner |
| jinja_options | {} | Extra options passed to Jinja2 environment |
* * *
## URL Routing Methods
| Method | Signature | Description |
| --- | --- | --- |
| route | (rule, **options) | Decorator, binds a URL rule to a view function |
| get | (rule, **options) | Decorator, binds only GET method (equivalent to methods=) |
| post | (rule, **options) | Decorator, binds only POST method |
| put | (rule, **options) | Decorator, binds only PUT method |
| delete | (rule, **options) | Decorator, binds only DELETE method |
| patch | (rule, **options) | Decorator, binds only PATCH method |
| add_url_rule | (rule, endpoint, view_func, provide_automatic_options, **options) | Programmatically add URL rule. The route decorator internally calls this method |
| url_for | (endpoint, *, _anchor, _method, _scheme, _external, **values) | Generate URL based on endpoint and parameters. In blueprints, endpoint needs blueprint name prefix |
| register_blueprint | (blueprint, **options) | Register a blueprint, can specify url_prefix, subdomain and other override parameters |
| iter_blueprints | () | Iterate through all blueprints in registration order |
> The 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.
| Method | Execution Time | Return Non-None Behavior | Typical Use |
| --- | --- | --- | --- |
| before_request | Before route dispatch | Return value is used as final response, view function is skipped | Login check, permission verification |
| after_request | After response is built, before sending | Must receive and return Response object | Add security headers, CORS headers |
| teardown_request | When request context pops | Return value is ignored | Release request-level resources |
| teardown_appcontext | When application context pops | Return value is ignored | Close database connections |
| errorhandler | When specified status code or exception occurs | Return value is used as error page response | Custom 404/500 pages |
| url_value_preprocessor | After URL variables are extracted, before view is called | Return value is ignored | Preprocess URL parameters |
| url_defaults | When url_for builds URL | Modify the values dictionary passed in | Add 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 | Return dict, merged into shell context | Pre-import common objects into flask shell |
* * *
## Request Processing Methods
The following methods are internally called 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 URL, calls corresponding view function |
| make_response(rv) | Converts view function return value to 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) | Complete request dispatch entry: preprocess β dispatch β finalize |
| handle_http_exception(ctx, e) | Handle HTTP exceptions, find corresponding errorhandler |
| handle_user_exception(ctx, e) | Handle user code exceptions, distinguish HTTP exceptions from regular exceptions |
| handle_exception(ctx, e) | Final exception handling, returns 500 response |
| ensure_sync(func) | Ensure function executes synchronously. Async functions are wrapped to be synchronous
YouTip