Flask extension to integrate with shared cookie service.
Project description
Canonical Cookie Service Integration
A Flask extension for integrating with the Canonical shared cookie consent service. This package handles user consent preferences, session management, and synchronization with a central cookie service.
Installation
pip install canonicalwebteam.cookie_service
Or add to your requirements.txt:
canonicalwebteam.cookie-service
Frontend Dependency
This package requires the cookie-policy npm package (version 4.8.0 or above) for client-side cookie management:
Quick Start
from flask import Flask
from canonicalwebteam.cookie_service import CookieConsent
app = Flask(__name__)
# Required: Configure Flask session
app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(days=365)
app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
app.config["SESSION_COOKIE_HTTPONLY"] = True
# Set to false for local development (or just use dynamic app.debug)
app.config["SESSION_COOKIE_SECURE"] = True
# Required: Set up cache functions (see Cache Integration section)
def get_cache(key):
return your_cache.get(key)
def set_cache(key, value, timeout):
your_cache.set(key, value, timeout)
# Initialize the cookie consent service
cookie_service = CookieConsent().init_app(
app,
get_cache_func=get_cache,
set_cache_func=set_cache,
start_health_check=True, # Optional: default True
auto_register_hooks=True, # Optional: default True
)
Configuration
Required Environment Variables
export COOKIE_SERVICE_API_KEY="your-api-key-here"
Optional Configuration
These can be set in your Flask app config and have the following defaults:
# URL of the central cookie service (default: production)
app.config["CENTRAL_COOKIE_SERVICE_URL"] = "https://cookies.canonical.com"
# Number of days before preference cookies expire (default: 365)
app.config["PREFERENCES_COOKIE_EXPIRY_DAYS"] = 365
Cache Integration
The package requires integration with a caching system to store the health check status of the cookie service. This prevents excessive API calls and improves performance.
Cache Function Requirements
You must provide two functions:
get_cache_func(key)
Retrieves a value from the cache.
- Parameters:
key(str) - The cache key - Returns: The cached value or
Noneif not found
set_cache_func(key, value, timeout)
Stores a value in the cache with a timeout.
- Parameters:
key(str) - The cache keyvalue(any) - The value to cachetimeout(int) - TTL in seconds
Using Flask-Caching:
from flask_caching import Cache
cache = Cache(app, config={'CACHE_TYPE': 'redis'})
def get_cache(key):
return cache.get(key)
def set_cache(key, value, timeout):
cache.set(key, value, timeout=timeout)
Initialization Parameters
init_app(app, get_cache_func, set_cache_func, start_health_check=True, auto_register_hooks=True)
Required Parameters:
app: Flask application instanceget_cache_func: Function to retrieve cached values (see Cache Integration)set_cache_func: Function to store cached values (see Cache Integration)
Optional Parameters:
-
start_health_check(bool, default:True)- Starts a background thread that pings the cookie service every 15 seconds
- The health status is cached and used to determine whether to redirect users to the service
- Set to
Falseto disable health checks (not recommended for production) - Common pattern:
start_health_check=not app.debug(only run in production)
-
auto_register_hooks(bool, default:True)- Automatically registers Flask
@before_requestand@after_requesthooks - When
True, the package handles session checks and cookie synchronization automatically - Set to
Falseif you need manual control over the request/response cycle (advanced use case)
- Automatically registers Flask
How It Works
The system works by creating a session within the central service with an ID. This same session is created on each site the user visits, creating an association. This ID can then be used to fetch preferences.
1. Session Creation Flow
- User visits your site
- The
@before_requesthook checks if the cookie service is health and a session exists - If no session exists, user is redirected to the central cookie service
- The cookie service creates a session and redirects back to
/cookies/callback?code=... - The callback exchanges the code for a
user_uuidand stores it in the session - User is redirected back to their original destination
2. Preference Synchronization
The @after_request hook:
- Checks if the
_cookies_accepted_tsis over 1 day old - If it is, fetches the user's consent preferences from the service
- Syncs preferences to local cookies (
_cookies_accepted)
Routes Provided
The package automatically registers the following routes under /cookies:
/cookies/callback- Handles OAuth-style callback from the central service/cookies/get-preferences- API endpoint to fetch current user's preferences/cookies/set-preferences- API endpoint to update current user's preferences (called by cookie-policy package)
Cookies Set by This Package
| Cookie Name | Purpose | Lifetime | Attributes |
|---|---|---|---|
session |
Flask session containing user_uuid |
365 days | HttpOnly, Secure, SameSite=Lax |
_cookies_accepted |
User's consent preferences | 365 days | Secure, SameSite=Lax |
_cookies_accepted_ts |
Timestamp of last preference update | 365 days | Secure, SameSite=Lax |
_cookies_service_up |
Indicates if service is healthy | Session | Secure, SameSite=Lax |
_cookies_redirect_completed |
Prevents redirect loops | Session | Secure, SameSite=Lax |
Advanced Usage
Manual Hook Registration
If you need more control over the request/response cycle, you can set auto_register_hooks=False.
This allows you to define custom cycle hooks:
from canonicalwebteam.cookie_service.helpers import (
check_session_and_redirect,
sync_preferences_cookie,
)
@app.before_request
def my_before_request():
# Your custom logic here
response = check_session_and_redirect()
if response:
return response
@app.after_request
def my_after_request(response):
# Your custom logic here
response = sync_preferences_cookie(response)
return response
Support
- Report issues: GitHub Issues
- Reach out to Web Engineering.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters