Overview
The Flask application object is the central component of any Flask application. It acts as a registry for view functions, URL rules, template configuration, and much more.Creating an Application
The most basic Flask application is created by instantiating theFlask class:
The Import Name Parameter
The__name__ parameter is crucial as it helps Flask:
- Locate resources (templates, static files)
- Provide better debugging information
- Help extensions determine the application’s location
For single-module applications, always use
__name__. For packages, you can hardcode the package name:Application Configuration
Flask provides a rich set of configuration options through theconfig attribute:
Default Configuration
Flask comes with sensible defaults (fromapp.py:206-238):
Application Structure
Static Files
By default, Flask serves static files from astatic folder:
/static/<path:filename> to serve these files.
Templates
Templates are served from thetemplates folder by default:
Running the Application
Development Server
For development, use the built-in server:Command Line Interface
Flask also provides CLI commands:Application Methods
Resource Management
Open files relative to the application root:Test Client
Create a test client for testing:Application Lifecycle
First Request
Flask tracks whether the first request has been handled via the_got_first_request flag (from app.py:999-1010).
Request Processing Flow
- Request Started - Signal sent
- Before Request - Run preprocessing functions
- Dispatch Request - Match URL and call view function
- After Request - Process response
- Teardown - Clean up resources
Custom Application Classes
You can subclassFlask to customize behavior:
Application Factory Pattern
For larger applications, use the application factory pattern:Best Practices
Use Application Factory
Create apps with factory functions for better testing and multiple instances
Configuration Management
Keep sensitive config in environment variables, not in code
Error Handling
Always register error handlers for production applications
Logging
Use app.logger for consistent logging across your application
Related Concepts
- Application Context - Understanding app contexts
- Blueprints - Modular application structure
- Routing - URL routing and view functions
