A simple framework for building complex web applications.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
The Flask application class provides the central registry for views, URL rules, template configuration and much more. It implements a WSGI application and serves as the main entry point for Flask web applications.
The main application class that implements a WSGI application and acts as the central registry for routing, configuration, and extensions.
class Flask:
def __init__(
self,
import_name: str,
static_url_path: str | None = None,
static_folder: str | os.PathLike[str] | None = "static",
static_host: str | None = None,
host_matching: bool = False,
subdomain_matching: bool = False,
template_folder: str | os.PathLike[str] | None = "templates",
instance_path: str | None = None,
instance_relative_config: bool = False,
root_path: str | None = None,
):
"""
Create a Flask application.
Args:
import_name: Name of the application package (usually __name__)
static_url_path: URL path for static files (defaults to '/static')
static_folder: Folder containing static files relative to app
static_host: Host to use when generating static file URLs
host_matching: Enable host matching for URLs
subdomain_matching: Enable subdomain matching for URLs
template_folder: Folder containing templates relative to app
instance_path: Path to instance folder for configuration/data files
instance_relative_config: Load config relative to instance path
root_path: Path to the root of the application
"""Core properties available on Flask application instances.
class Flask:
# Application identification
name: str # Application name
import_name: str # Import name passed to constructor
# Configuration and debugging
config: Config # Configuration dictionary
debug: bool # Debug mode flag
testing: bool # Testing mode flag
secret_key: str | bytes | None # Secret key for sessions/cookies
# Template and static file handling
jinja_env: Environment # Jinja2 environment
static_folder: str | None # Static files folder path
static_url_path: str | None # URL path for static files
template_folder: str | None # Templates folder path
# URL routing
url_map: Map # URL routing map
view_functions: dict[str, Callable] # Registered view functions
# Request handling
before_request_funcs: dict # Before request handlers
after_request_funcs: dict # After request handlers
teardown_request_funcs: dict # Request teardown handlers
teardown_appcontext_funcs: list # App context teardown handlers
# Extensions and customization
extensions: dict # Registered extensions
blueprints: dict[str, Blueprint] # Registered blueprints
json: JSONProvider # JSON provider instance
# Session configuration
permanent_session_lifetime: timedelta # Permanent session lifetime
session_interface: SessionInterface # Session interface
# Error handling
error_handler_spec: dict # Error handler specifications
# Logging
logger: Logger # Application loggerMethods for running and managing the Flask application lifecycle.
def run(
self,
host: str | None = None,
port: int | None = None,
debug: bool | None = None,
load_dotenv: bool = True,
**options
) -> None:
"""
Run the application using the development server.
Args:
host: Hostname to listen on (defaults to '127.0.0.1')
port: Port to listen on (defaults to 5000)
debug: Enable debug mode
load_dotenv: Load environment variables from .env file
**options: Additional options passed to werkzeug server
"""
def wsgi_app(self, environ: dict, start_response: Callable) -> Iterator[bytes]:
"""
The actual WSGI application called by the WSGI server.
Args:
environ: WSGI environment dictionary
start_response: WSGI start_response callable
Returns:
Iterator of response bytes
"""Methods for creating and managing application and request contexts.
def app_context(self) -> AppContext:
"""
Create an application context.
Returns:
Application context manager
"""
def request_context(self, environ: dict) -> RequestContext:
"""
Create a request context from WSGI environment.
Args:
environ: WSGI environment dictionary
Returns:
Request context manager
"""
def test_request_context(self, *args, **kwargs) -> RequestContext:
"""
Create a request context for testing.
Args:
*args: Arguments passed to EnvironBuilder
**kwargs: Keyword arguments passed to EnvironBuilder
Returns:
Request context manager for testing
"""Methods for creating test clients and runners for application testing.
def test_client(self, use_cookies: bool = True, **kwargs) -> FlaskClient:
"""
Create a test client for the application.
Args:
use_cookies: Enable cookie support in test client
**kwargs: Additional arguments passed to test client class
Returns:
Test client instance
"""
def test_cli_runner(self, **kwargs) -> FlaskCliRunner:
"""
Create a CLI test runner for the application.
Args:
**kwargs: Additional arguments passed to CLI runner
Returns:
CLI test runner instance
"""Methods for creating and processing responses.
def make_response(self, rv) -> Response:
"""
Convert a return value to a Response object.
Args:
rv: Return value (str, bytes, dict, list, tuple, Response, etc.)
Returns:
Response object
"""
def make_default_options_response(self) -> Response:
"""
Create a default OPTIONS response.
Returns:
Response with allowed methods in Allow header
"""Methods for handling request processing lifecycle.
def dispatch_request(self) -> ResponseReturnValue:
"""
Match the URL and dispatch to view function.
Returns:
Return value from view function
"""
def full_dispatch_request(self) -> Response:
"""
Complete request dispatch with pre/post processing.
Returns:
Final response object
"""
def preprocess_request(self) -> ResponseReturnValue | None:
"""
Run before_request handlers.
Returns:
Response if handler returned one, None otherwise
"""
def process_response(self, response: Response) -> Response:
"""
Run after_request handlers on response.
Args:
response: Response object to process
Returns:
Processed response object
"""
def finalize_request(
self,
rv: ResponseReturnValue,
from_error_handler: bool = False
) -> Response:
"""
Convert return value to Response and finalize.
Args:
rv: Return value from view or error handler
from_error_handler: Whether rv came from error handler
Returns:
Final response object
"""Methods for handling exceptions and HTTP errors.
def handle_exception(self, e: Exception) -> Response:
"""
Handle any uncaught exception.
Args:
e: Exception that was raised
Returns:
Error response
"""
def handle_http_exception(self, e: HTTPException) -> Response:
"""
Handle HTTP exceptions.
Args:
e: HTTP exception
Returns:
Error response
"""
def handle_user_exception(self, e: Exception) -> Response:
"""
Handle exceptions in user code.
Args:
e: Exception from user code
Returns:
Error response
"""
def log_exception(self, exc_info) -> None:
"""
Log an exception to the application logger.
Args:
exc_info: Exception info tuple
"""Methods for serving static files.
def send_static_file(self, filename: str) -> Response:
"""
Send a static file from the static folder.
Args:
filename: Filename relative to static folder
Returns:
Response with file contents
"""
def get_send_file_max_age(self, filename: str | None) -> int | None:
"""
Get max age for static file caching.
Args:
filename: Static filename
Returns:
Max age in seconds or None
"""Methods for customizing the interactive shell context.
def make_shell_context(self) -> dict[str, Any]:
"""
Create shell context with application globals.
Returns:
Dictionary of names available in shell
"""
def shell_context_processor(self, f: Callable) -> Callable:
"""
Decorator to register shell context processor.
Args:
f: Function that returns dict of shell context variables
Returns:
The original function
"""from flask import Flask
# Create application
app = Flask(__name__)
app.secret_key = 'your-secret-key-here'
# Configure application
app.config['DEBUG'] = True
app.config['TESTING'] = False
# Basic route
@app.route('/')
def home():
return 'Hello World!'
# Run application
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000, debug=True)from flask import Flask
import os
# Create application with custom folders
app = Flask(
__name__,
static_folder='assets',
static_url_path='/assets',
template_folder='templates'
)
# Load configuration
app.config.from_object('config.DevelopmentConfig')
app.config.from_envvar('APP_SETTINGS', silent=True)
# Set up logging
if not app.debug:
import logging
from logging.handlers import RotatingFileHandler
file_handler = RotatingFileHandler('app.log', maxBytes=10240, backupCount=10)
file_handler.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
))
file_handler.setLevel(logging.INFO)
app.logger.addHandler(file_handler)
app.logger.setLevel(logging.INFO)import pytest
from flask import Flask
@pytest.fixture
def app():
app = Flask(__name__)
app.config['TESTING'] = True
app.config['SECRET_KEY'] = 'test-key'
@app.route('/')
def index():
return 'Hello Test!'
return app
@pytest.fixture
def client(app):
return app.test_client()
@pytest.fixture
def runner(app):
return app.test_cli_runner()
def test_index(client):
response = client.get('/')
assert response.status_code == 200
assert response.data == b'Hello Test!'Install with Tessl CLI
npx tessl i tessl/pypi-flask