Cloudflare D1 — django_cf
django_cf is an auto-configuring module that connects Django to Cloudflare D1 — SQLite-over-HTTP served at the edge. It handles credential management, schema migration, user sync, and provides the D1Q SQL factory used by other modules (including django_monitor).
Architecture
Key Concepts
D1 is SQLite-over-HTTP. There’s no persistent connection — every query is an HTTP request to the Cloudflare API. CloudflareD1Client wraps the official cloudflare Python SDK.
D1Q is the SQL factory. Define a table once with D1Table (columns, PK, indexes, conflict strategy), then call D1Q.upsert(TABLE, data) to get (sql, params). No raw SQL strings anywhere.
BaseD1Service is the abstract base for all D1-backed services. Provides _get_client(), _get_api_url(), and _ensure_schema(). Both UserSyncService (users) and MonitorSyncService (monitor events) inherit from it.
Quick Start
1. Install credentials
# .env.secrets
CF_ACCOUNT_ID=your-account-id
CF_API_TOKEN=your-d1-edit-token
CF_D1_DATABASE_ID=your-database-uuid2. Add to config
# djangoconfig.py
from django_cfg import CloudflareConfig
class MyConfig(DjangoConfig):
cloudflare: CloudflareConfig = CloudflareConfig(
enabled=True,
account_id="${CF_ACCOUNT_ID}",
api_token="${CF_API_TOKEN}",
d1_database_id="${CF_D1_DATABASE_ID}",
)Django-CFG registers DjangoCfConfig automatically. On startup it:
- Connects
post_savesignal for user sync - Connects
django_monitorcapture hooks (if monitor module is present) - Runs
_ensure_schema()lazily on first use
3. Verify
python manage.py cf_statusWhat Gets Synced
| Table | Trigger | Method |
|---|---|---|
users | post_save → RQ task | UserSyncService.push_user() — upsert |
users (bulk) | cf_sync_users command | full_sync_users() — batched upsert |
projects | startup (planned) | metadata upsert |
What’s Next
CloudflareConfig fields and env varsD1Q — SQL FactoryHow to define tables and generate SQL with D1QUser SyncSync flow, bulk sync, and RQ task detailsMonitor ModuleError tracking built on top of django_cfTAGS: django_cf, cloudflare-d1, user-sync, edge-database DEPENDS_ON: []