app/__init__.py module provides the foundational setup for the Document Download Frontend application, including Flask app initialization, security headers, CSRF protection, and custom URL converters.
Main Functions
create_app
Initializes the Flask application with configuration, blueprints, and middleware.Flask application instance to configure
- Loads configuration from
NOTIFY_ENVIRONMENTenvironment variable - Registers
Base64UUIDConverterfor URL routing - Initializes metrics, Jinja templates, StatsD client, and logging
- Registers main blueprint with routes
- Sets up error handlers
init_app
Configures request lifecycle hooks and template context.Flask application instance
after_request: Adds security headers viauseful_headers_after_requestbefore_request: Generates CSP nonce viamake_nonce_before_requestcontext_processor: Injects global template variables (asset_path, header_colour, asset_url)
Security Functions
make_nonce_before_request
Generates a cryptographically secure nonce for Content Security Policy.- Uses
secrets.token_urlsafe(16)for secure random generation - Stored in
request.csp_noncefor template inline scripts
useful_headers_after_request
Adds comprehensive security headers to every response.Flask response object
Modified response with security headers
Error Handlers
register_errorhandlers
Registers comprehensive error handling for HTTP errors and exceptions.Flask application instance
- 400, 401, 403, 404, 410: Renders corresponding error template
- 500, Exception: Logs exception, shows debug stacktrace in DEBUG mode
- CSRFError: Logs CSRF attempt, renders 500 template with 400 status
- EventletTimeout: Logs timeout, returns 504 error
URL Converters
Base64UUIDConverter
Custom Werkzeug converter for base64-encoded UUIDs in URLs.to_python
Converts base64 URL parameter to UUID.Base64-encoded UUID from URL
Decoded UUID object
ValidationError if value cannot be decoded
to_url
Converts UUID to base64 string for URL generation.UUID object to encode
Base64-encoded UUID string
Client Initialization
service_api_client
Thread-safe proxy to ServiceApiClient instance.- Uses
ContextVarfor thread-local storage - Lazy initialization via
LazyLocalGetter - Proxied through
LocalProxyfor transparent access
reset_memos
Resets all memoized/cached client instances.Template Configuration
init_jinja
Configures Jinja2 template loader with application and GOV.UK Frontend templates.Flask application instance
app/templates: Application-specific templatesgovuk_frontend_jinja: GOV.UK Design System components