django-cloud-backup 0.1.0__tar.gz → 0.1.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. django_cloud_backup-0.1.2/PKG-INFO +976 -0
  2. django_cloud_backup-0.1.2/README.md +938 -0
  3. django_cloud_backup-0.1.2/cloud_backup/admin.py +29 -0
  4. django_cloud_backup-0.1.2/cloud_backup/backup.py +243 -0
  5. django_cloud_backup-0.1.2/cloud_backup/backup_azure.py +238 -0
  6. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/cloud_backup/backup_db.py +118 -12
  7. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/cloud_backup/backup_local_files.py +53 -0
  8. django_cloud_backup-0.1.2/cloud_backup/config.py +298 -0
  9. django_cloud_backup-0.1.2/cloud_backup/db_tiers.py +340 -0
  10. django_cloud_backup-0.1.2/cloud_backup/enhanced_views.py +882 -0
  11. django_cloud_backup-0.1.2/cloud_backup/management/commands/backup_status.py +30 -0
  12. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/cloud_backup/management/commands/backup_website.py +39 -3
  13. django_cloud_backup-0.1.2/cloud_backup/management/commands/storage_setup.py +48 -0
  14. django_cloud_backup-0.1.2/cloud_backup/migrations/0001_initial.py +32 -0
  15. django_cloud_backup-0.1.2/cloud_backup/migrations/__init__.py +0 -0
  16. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/cloud_backup/modals.py +43 -29
  17. django_cloud_backup-0.1.2/cloud_backup/models.py +57 -0
  18. django_cloud_backup-0.1.2/cloud_backup/runs.py +76 -0
  19. django_cloud_backup-0.1.2/cloud_backup/sql_functions.py +89 -0
  20. django_cloud_backup-0.1.2/cloud_backup/status.py +528 -0
  21. django_cloud_backup-0.1.2/cloud_backup/storage_setup.py +616 -0
  22. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/cloud_backup/storages/__init__.py +16 -0
  23. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/cloud_backup/storages/azure.py +26 -2
  24. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/cloud_backup/storages/base.py +89 -6
  25. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/cloud_backup/storages/gdrive.py +21 -2
  26. django_cloud_backup-0.1.2/cloud_backup/storages/s3.py +595 -0
  27. django_cloud_backup-0.1.2/cloud_backup/tasks.py +126 -0
  28. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/cloud_backup/templates/cloud_backup/backup_content.html +3 -1
  29. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/cloud_backup/templates/cloud_backup/info.html +5 -3
  30. django_cloud_backup-0.1.2/cloud_backup/templates/cloud_backup/runs_content.html +7 -0
  31. django_cloud_backup-0.1.2/cloud_backup/templates/cloud_backup/storage_setup_content.html +13 -0
  32. django_cloud_backup-0.1.2/cloud_backup/tests/__init__.py +0 -0
  33. django_cloud_backup-0.1.2/cloud_backup/tests/test_backup_azure.py +223 -0
  34. django_cloud_backup-0.1.2/cloud_backup/tests/test_db_tiers.py +185 -0
  35. django_cloud_backup-0.1.2/cloud_backup/tests/test_extensions.py +130 -0
  36. django_cloud_backup-0.1.2/cloud_backup/tests/test_s3_trash.py +83 -0
  37. django_cloud_backup-0.1.2/cloud_backup/tests/test_status.py +477 -0
  38. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/cloud_backup/urls.py +24 -6
  39. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/cloud_backup/utils.py +2 -0
  40. django_cloud_backup-0.1.2/cloud_backup/views.py +72 -0
  41. django_cloud_backup-0.1.2/django_cloud_backup.egg-info/PKG-INFO +976 -0
  42. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/django_cloud_backup.egg-info/SOURCES.txt +19 -0
  43. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/django_cloud_backup.egg-info/requires.txt +1 -1
  44. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/pyproject.toml +21 -2
  45. django_cloud_backup-0.1.0/PKG-INFO +0 -439
  46. django_cloud_backup-0.1.0/README.md +0 -416
  47. django_cloud_backup-0.1.0/cloud_backup/backup.py +0 -109
  48. django_cloud_backup-0.1.0/cloud_backup/config.py +0 -87
  49. django_cloud_backup-0.1.0/cloud_backup/enhanced_views.py +0 -273
  50. django_cloud_backup-0.1.0/cloud_backup/sql_functions.py +0 -46
  51. django_cloud_backup-0.1.0/cloud_backup/storages/s3.py +0 -256
  52. django_cloud_backup-0.1.0/cloud_backup/tasks.py +0 -82
  53. django_cloud_backup-0.1.0/cloud_backup/views.py +0 -43
  54. django_cloud_backup-0.1.0/django_cloud_backup.egg-info/PKG-INFO +0 -439
  55. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/LICENSE +0 -0
  56. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/MANIFEST.in +0 -0
  57. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/cloud_backup/__init__.py +0 -0
  58. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/cloud_backup/apps.py +0 -0
  59. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/cloud_backup/backup_azure_s3.py +0 -0
  60. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/cloud_backup/backup_s3.py +0 -0
  61. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/cloud_backup/base_backup.py +0 -0
  62. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/cloud_backup/compression.py +0 -0
  63. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/cloud_backup/encryption.py +0 -0
  64. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/cloud_backup/management/__init__.py +0 -0
  65. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/cloud_backup/management/commands/__init__.py +0 -0
  66. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/cloud_backup/management/commands/restore_db.py +0 -0
  67. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/cloud_backup/prune_backups.py +0 -0
  68. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/cloud_backup/templates/cloud_backup/backup.html +0 -0
  69. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/django_cloud_backup.egg-info/dependency_links.txt +0 -0
  70. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/django_cloud_backup.egg-info/top_level.txt +0 -0
  71. {django_cloud_backup-0.1.0 → django_cloud_backup-0.1.2}/setup.cfg +0 -0
@@ -0,0 +1,976 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-cloud-backup
3
+ Version: 0.1.2
4
+ Summary: Backs up django postgres databases, local folders and S3 folders to Google Drive, S3-compatible storage (AWS, Backblaze B2, Cloudflare R2) or Azure Blob Storage.
5
+ Author: Ian Jones
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/jonesim/django-cloud-backup
8
+ Project-URL: Documentation, https://github.com/jonesim/django-cloud-backup#readme
9
+ Project-URL: Changelog, https://github.com/jonesim/django-cloud-backup/releases
10
+ Project-URL: Issues, https://github.com/jonesim/django-cloud-backup/issues
11
+ Project-URL: Source, https://github.com/jonesim/django-cloud-backup
12
+ Keywords: django,backup,postgres,postgresql,ransomware,immutable,object-lock,worm,s3,backblaze,b2,cloudflare-r2,azure,google-drive,disaster-recovery
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Environment :: Web Environment
15
+ Classifier: Framework :: Django
16
+ Classifier: Framework :: Django :: 5.2
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: Intended Audience :: System Administrators
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Topic :: Database
21
+ Classifier: Topic :: Security
22
+ Classifier: Topic :: System :: Archiving :: Backup
23
+ Classifier: Topic :: System :: Systems Administration
24
+ Classifier: Operating System :: OS Independent
25
+ Requires-Python: >=3.8
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Requires-Dist: encrypted-credentials
29
+ Requires-Dist: google-client-helper>=0.0.4
30
+ Requires-Dist: requests
31
+ Provides-Extra: s3
32
+ Requires-Dist: boto3; extra == "s3"
33
+ Provides-Extra: azure
34
+ Requires-Dist: azure-storage-blob; extra == "azure"
35
+ Provides-Extra: encryption
36
+ Requires-Dist: cryptography; extra == "encryption"
37
+ Dynamic: license-file
38
+
39
+ # django-cloud-backup
40
+
41
+ [![PyPI version](https://badge.fury.io/py/django-cloud-backup.svg)](https://badge.fury.io/py/django-cloud-backup)
42
+
43
+ **Django backups that survive your credentials being stolen.**
44
+
45
+ Backs up PostgreSQL databases, local folders, S3 buckets and Azure containers to Google
46
+ Drive, S3-compatible storage (AWS, Backblaze B2, Cloudflare R2) or Azure Blob Storage -
47
+ and then holds them down so that whoever gets into your server cannot destroy them.
48
+
49
+ An attacker who reaches your settings has your backup credentials too. The usual
50
+ arrangement - scheduled dumps to a bucket the application can delete from - fails at
51
+ exactly the moment it is needed: the backups are wiped, or quietly overwritten with
52
+ encrypted copies on the next scheduled run. This package is built for that threat model.
53
+
54
+ ## What it does that a scheduled dump does not
55
+
56
+ - **Object Lock retention stamped at upload.** Every dump is immutable for a fixed window,
57
+ topped up by a scheduled task; in `COMPLIANCE` mode not even the bucket owner can shorten
58
+ it. See [Ransomware protection](#ransomware-protection).
59
+ - **An application that never deletes.** With `BACKUP_DB_TIERS` dumps are promoted between
60
+ hourly/daily/monthly prefixes by server-side copy and the bucket's own lifecycle rules do
61
+ all the expiry, so the backup credential needs no delete permission at all. See
62
+ [Lifecycle-managed database backups](#lifecycle-managed-database-backups-s3b2r2).
63
+ - **Changed source files cannot silently overwrite good backups.**
64
+ `BACKUP_CHANGED_FILES = 'protect'` refuses the overwrite and fails the run; `'history'`
65
+ keeps the previous version first. See [Ransomware protection](#ransomware-protection).
66
+ - **Read-only destinations.** A config marked `restore_only` refuses every write and
67
+ generates a read-only key - for the staging box that shares an encrypted settings file
68
+ with live. See [Live, staging and local machines](#live-staging-and-local-machines).
69
+ - **It verifies the bucket is actually configured that way.** The management page queries
70
+ the destination and reports versioning, soft delete, Object Lock and lifecycle rules, and
71
+ flags any hidden version or overwrite the retention policy cannot explain. See
72
+ [Setting up the bucket](#setting-up-the-bucket).
73
+ - **It tells you when the backups stop being current.** Every run is recorded and graded
74
+ against your `CELERY_BEAT_SCHEDULE`, browsable in a Run Log page and served as json at
75
+ `backup/status/` for a monitoring agent. See
76
+ [Checking that the backups are current](#checking-that-the-backups-are-current).
77
+ - **Optional client-side AES-256-GCM encryption**, so the destination never holds
78
+ plaintext. See [Client-side encryption](#client-side-encryption).
79
+
80
+ Alongside that: a Django management UI for browsing, verifying and restoring backups,
81
+ Celery tasks for scheduling, MD5/ETag deduplication, per-schema database backups, and
82
+ several named destinations in one project.
83
+
84
+ A schema dump (`pg_dump -n`) does not include the extensions installed in that schema, so
85
+ each schema dump records their names in its metadata (`extensions`, e.g. `pg_trgm`), and
86
+ restoring it creates any that are missing first. Only extensions installed *in* that
87
+ schema are recorded: one in `public` used by a tenant schema needs `public` restored
88
+ first, and a restore warns when a recorded extension is installed in a different schema.
89
+ The **Drop Restore** button, which runs `DROP SCHEMA ... CASCADE` and so removes the
90
+ extensions too, notes them before dropping and recreates them afterwards in the same
91
+ transaction, which also covers dumps made before this was recorded.
92
+
93
+ ## Install
94
+
95
+ pip install django-cloud-backup # Google Drive destination
96
+ pip install django-cloud-backup[s3] # AWS S3, Backblaze B2, Cloudflare R2
97
+ pip install django-cloud-backup[azure] # Azure Blob Storage
98
+ pip install django-cloud-backup[encryption] # client-side encryption
99
+
100
+ settings.py:
101
+
102
+ INSTALLED_APPS = ['cloud_backup', ...]
103
+ BACKUP_ROOT = 'django_backup'
104
+
105
+ Google Drive is the default destination and needs a service account - the setup walkthrough
106
+ starts below. To back up to a bucket instead, set `BACKUP_STORAGE`; see
107
+ [Choosing a backup destination](#choosing-a-backup-destination).
108
+
109
+ Already running `django-gdrive-backup`? See
110
+ [Migrating from django-gdrive-backup](#migrating-from-django-gdrive-backup) at the end.
111
+
112
+ ## Setup
113
+
114
+ The walkthrough below configures the default Google Drive destination.
115
+ For a bucket destination, skip to [Choosing a backup destination](#choosing-a-backup-destination).
116
+
117
+ ## encrypted-credentials
118
+
119
+ This package uses encrypted-credentials and the instructions there could be useful. Adding the following lines to **settings.py** will initialise the package
120
+
121
+ from encrypted_credentials.django_credentials import add_encrypted_settings
122
+
123
+ add_encrypted_settings(globals())
124
+
125
+
126
+ ## Create service account
127
+
128
+ Requires a Google service account with the Google Drive API enabled
129
+
130
+ https://console.cloud.google.com/apis/credentials/serviceaccountkey
131
+
132
+ ## Add to cloud_backup installed apps
133
+
134
+ settings.py
135
+
136
+ INSTALLED_APPS = [ ..
137
+ 'cloud_backup',
138
+ ]
139
+
140
+ ## Store service account key
141
+
142
+ By default *encrypted-credentials* is used to store the key. Create a directory off the django projects BASE_DIR called credentials and save the json key.
143
+
144
+ settings.py
145
+
146
+ CREDENTIAL_FOLDER = os.path.join(BASE_DIR, 'credentials')
147
+ CREDENTIAL_FILES = {
148
+ 'drive': 'service-account.json',
149
+ }
150
+
151
+
152
+ ## Create Google Drive folder and share with service account
153
+
154
+ With a Google Drive account create a folder and share with the email address of the service account.
155
+
156
+
157
+ ## Ensure psql is available to python subprocess
158
+
159
+ For docker containers you may need to something similar to the following line in the Dockerfile dependent on the version of Postgres.
160
+
161
+ RUN apt-get -y install postgresql-client-11
162
+
163
+ ## Configure database backup
164
+
165
+ settings.py
166
+
167
+ BACKUP_ROOT = 'django_backup'
168
+
169
+ ## Choosing a backup destination
170
+
171
+ Google Drive is the default destination and needs no extra settings beyond those above.
172
+ Backups can instead be stored on any S3-compatible service or Azure Blob Storage by adding
173
+ a `BACKUP_STORAGE` dict to settings.py. The optional `root` key replaces `BACKUP_ROOT`
174
+ as the top-level folder/prefix.
175
+
176
+ AWS S3:
177
+
178
+ BACKUP_STORAGE = {
179
+ 'backend': 's3',
180
+ 'bucket': 'my-backups',
181
+ 'access_key_id': '...',
182
+ 'secret_key': '...',
183
+ 'root': 'django_backup',
184
+ }
185
+
186
+ Backblaze B2 (the S3 endpoint is discovered from the key automatically):
187
+
188
+ BACKUP_STORAGE = {
189
+ 'backend': 's3',
190
+ 'b2': True,
191
+ 'bucket': 'my-backups',
192
+ 'access_key_id': '...', # B2 keyID
193
+ 'secret_key': '...', # B2 applicationKey
194
+ }
195
+
196
+ Cloudflare R2:
197
+
198
+ BACKUP_STORAGE = {
199
+ 'backend': 's3',
200
+ 'bucket': 'my-backups',
201
+ 'endpoint_url': 'https://<account-id>.r2.cloudflarestorage.com',
202
+ 'region': 'auto',
203
+ 'access_key_id': '...',
204
+ 'secret_key': '...',
205
+ }
206
+
207
+ Azure Blob Storage:
208
+
209
+ BACKUP_STORAGE = {
210
+ 'backend': 'azure',
211
+ 'container': 'backups',
212
+ 'connection_string': '...', # or account_url + credential
213
+ }
214
+
215
+ S3 backends require `pip install django-cloud-backup[s3]` and Azure
216
+ `pip install django-cloud-backup[azure]`.
217
+
218
+ Note that unlike Google Drive, S3 and Azure destinations have no trash - pruned
219
+ database backups are deleted permanently, so consider enabling bucket versioning
220
+ (S3/B2/R2 lifecycle rules) or soft delete (Azure) if you want a safety net. The
221
+ backup page queries the destination and shows whether versioning, soft delete and
222
+ Object Lock/immutability (WORM) are actually enabled, so a missing safety net is
223
+ visible at a glance.
224
+
225
+ ## Ransomware protection
226
+
227
+ If backups re-sync whenever a source file changes, an attacker encrypting your files
228
+ would overwrite the good backups on the next scheduled run. Protection is layered:
229
+
230
+ *Changed-file handling* - settings.py:
231
+
232
+ BACKUP_CHANGED_FILES = 'overwrite' # default: re-upload changed files
233
+ BACKUP_CHANGED_FILES = 'protect' # never touch the existing backup: skip the
234
+ # file, log a warning and fail the backup run
235
+ # (raises ChangedFilesError after everything
236
+ # else has completed, so monitoring alerts)
237
+ BACKUP_CHANGED_FILES = 'history' # keep the previous version (S3 server-side
238
+ # copy named <file>.<timestamp>, Azure
239
+ # snapshot, Google Drive rename), then upload
240
+ # the new version; warns but succeeds
241
+
242
+ Use `'protect'` when your file store is immutable (e.g. UUID-named uploads that are
243
+ never edited) - any change is corruption or an attacker. Use `'history'` when changes
244
+ can be legitimate but you still want every previous version recoverable.
245
+
246
+ *Object Lock retention (S3 and B2)* - create the bucket with Object Lock enabled and
247
+ add a `lock` section to `BACKUP_STORAGE`:
248
+
249
+ BACKUP_STORAGE = {
250
+ 'backend': 's3', ...,
251
+ 'lock': {
252
+ 'mode': 'COMPLIANCE', # not even the bucket owner can shorten or delete
253
+ 'db_days': 35, # each database dump is locked for 35 days at upload
254
+ 'file_days': 7, # each file backup is locked for 7 days at upload
255
+ 'min_days': 7, # extend_retention keeps every file locked >= 7 days ahead
256
+ },
257
+ }
258
+
259
+ Locking at upload costs nothing (extra headers on the existing request). To keep
260
+ long-lived file backups permanently locked, schedule the top-up task daily - it
261
+ extends any object whose remaining lock is below `min_days`:
262
+
263
+ CELERY_BEAT_SCHEDULE = {
264
+ 'extend_retention': {
265
+ 'task': 'cloud_backup.tasks.extend_retention',
266
+ 'schedule': crontab(hour=3, minute=0),
267
+ },
268
+ }
269
+
270
+ or run `python manage.py backup_website --extend_retention`. The top-up costs 1-2 API
271
+ calls per file (roughly a minute per 10,000 files), which is why it is a scheduled
272
+ task rather than part of every backup. Backups only become deletable `min_days` after
273
+ the top-up task stops running.
274
+
275
+ Pruning still works on a locked bucket: Object Lock buckets are versioned, so deleting
276
+ an old dump just writes a delete marker (allowed even while versions are locked) and
277
+ the locked versions physically remain. Add a bucket lifecycle rule such as "expire
278
+ noncurrent versions after 40 days" to clean them up once their lock has passed. The
279
+ same versioning means even `'overwrite'` mode cannot physically destroy data on a
280
+ locked bucket - the prior locked version survives underneath.
281
+
282
+ *Credential and bucket hardening* (outside this package):
283
+
284
+ - **AWS S3**: give the backup IAM user no `s3:DeleteObject`/`s3:PutBucketLifecycle`;
285
+ prune via lifecycle rules instead of `BACKUP_DB_RETENTION`
286
+ - **Backblaze B2**: use an application key without the `deleteFiles` capability
287
+ - **Azure**: enable blob soft delete or a container immutability policy
288
+ - **Google Drive**: deletes go to trash and are recoverable, but the service account
289
+ can empty the trash - treat the credential file accordingly
290
+
291
+ With delete-less credentials, pruning logs a warning instead of failing the backup;
292
+ leave `BACKUP_DB_RETENTION` unset and let bucket lifecycle rules do the pruning - the
293
+ tiered layout below is the supported way to do that.
294
+
295
+ ## Lifecycle-managed database backups (S3/B2/R2)
296
+
297
+ `BACKUP_DB_RETENTION` prunes from the application: it lists the dumps and deletes the
298
+ ones it does not want to keep. `BACKUP_DB_TIERS` is the alternative - the application
299
+ only ever writes, and the bucket's own lifecycle rules do all the deleting:
300
+
301
+ BACKUP_DB_TIERS = True # requires the 's3' backend
302
+ BACKUP_DB_RETENTION = [] # tiering replaces client-side pruning
303
+
304
+ Every dump then goes to a unique, date-partitioned key under `hourly/`, and a
305
+ scheduled job promotes one dump per day into `daily/` and one per month into
306
+ `monthly/` using server-side copies (no download, no re-upload, no egress):
307
+
308
+ <root>/db/hourly/2026/07/30/db_2026_07_30_14_05_37.dump expire after ~15 days
309
+ <root>/db/daily/20_117_165_6/db_2026-07-30.dump expire after ~91 days
310
+ <root>/db/monthly/20_117_165_6/db_2026-07.dump no rule - kept forever
311
+
312
+ The sub-folder is the server the dump came from (the `ip_address` metadata every dump
313
+ carries), and each server is promoted on its own: its last dump of the day becomes its
314
+ daily copy, its last daily copy of the month its monthly one. Several installations can
315
+ share one db folder - a staging server that restores from production's dumps, or a
316
+ developer's machine - and each keeps its own archive rather than whichever of them
317
+ dumped last overwriting the day's single copy. That is the same guarantee the
318
+ `BACKUP_DB_RETENTION` layout gives by pruning per server.
319
+
320
+ The retention you get is the lifecycle rules you create; this package never writes
321
+ them, so the backup credential needs neither `DeleteObject` nor
322
+ `PutBucketLifecycleConfiguration`. On AWS, two rules with `Expiration.Days` of 15 and
323
+ 91 filtered on the `hourly/` and `daily/` prefixes. On B2, rules are
324
+ `fileNamePrefix` + `daysFromUploadingToHiding` + `daysFromHidingToDeleting`, and B2
325
+ buckets always keep versions, so **both** numbers are needed or "expired" files are
326
+ merely hidden and go on being billed:
327
+
328
+ {"fileNamePrefix": "django_backup/db/hourly/", "daysFromUploadingToHiding": 15,
329
+ "daysFromHidingToDeleting": 1}
330
+ {"fileNamePrefix": "django_backup/db/daily/", "daysFromUploadingToHiding": 91,
331
+ "daysFromHidingToDeleting": 1}
332
+
333
+ B2 rejects overlapping rules, so an existing bucket-wide rule (empty prefix) has to go
334
+ before these can be added. The backup page reads the bucket's lifecycle configuration
335
+ and shows a row per tier, in red when `hourly/` has no rule (dumps accumulate forever)
336
+ or when a catch-all rule would expire the `monthly/` archive.
337
+
338
+ **Promotion runs at the end of every database backup**, so there is no second job that
339
+ has to be working for the backups to survive - the hourly tier expires by itself, and a
340
+ promotion step that quietly stopped would lose everything while the backups carried on
341
+ looking healthy. In that in-backup pass it only looks at days after the newest one
342
+ already promoted, which is normally two listings and no copies at all; after an outage it
343
+ catches every missed day up on the next backup.
344
+
345
+ It is still worth scheduling as well, so promotion happens on a day when no backup runs:
346
+
347
+ CELERY_BEAT_SCHEDULE = {
348
+ 'promote_db_tiers': {
349
+ 'task': 'cloud_backup.tasks.promote_db_tiers',
350
+ 'schedule': crontab(hour=1, minute=30),
351
+ },
352
+ }
353
+
354
+ or `python manage.py backup_website --promote_tiers`. That form does a full 14-day scan,
355
+ warns about days that had no dumps at all, and takes `--as_of YYYY-MM-DD` and `--days N`
356
+ to backfill further. It needs no database connection and re-running it is a no-op.
357
+
358
+ The setup page shows a **Tier promotion** row with the newest daily dump, red when
359
+ nothing has reached the daily tier for more than two days - the one failure that would
360
+ otherwise be invisible until the hourly rule caught up with it.
361
+
362
+ Notes:
363
+
364
+ - Tiers are created inside each database folder, so a schema backed up separately gets
365
+ `<root>/db/<schema>/hourly/...` and needs its own pair of lifecycle rules.
366
+ - Copies at the root of `daily/` and `monthly/` are from before promotion was per
367
+ server. They are left as they are, expire under the same rules, and count as that
368
+ day's (or month's) copy, so upgrading creates no duplicates.
369
+ - Not compatible with Object Lock (`lock` in `BACKUP_STORAGE`): a retention lock stops
370
+ lifecycle expiry, so locked hourly dumps would accumulate forever. Pick one.
371
+ - Dumps written before tiering was turned on stay listed and restorable where they
372
+ are; nothing is migrated or deleted.
373
+ - The web UI lists every tier, which means a metadata request per dump. Set
374
+ `BACKUP_DB_TIERS = {'hourly_days': 3}` to list only the last few days of the hourly
375
+ tier - it is a display window, not a retention setting.
376
+
377
+ **How long each tier is kept** defaults to 15 days hourly, 91 days daily and the monthly
378
+ archive indefinitely. Change it per config, and the setup page generates the matching
379
+ rules and checks the real ones against them:
380
+
381
+ BACKUP_DB_TIERS = {'expire_days': {'monthly': 2557}} # end of month for 7 years
382
+ BACKUP_DB_TIERS = {'expire_days': {'hourly': 30, 'daily': 180, 'monthly': None}}
383
+
384
+ `None` means no rule at all, so that tier is kept until someone deletes it. By default the
385
+ application never applies these numbers - the destination's own rules are what actually
386
+ delete, and the page reads them back: a rule that expires a tier *sooner* than the config
387
+ asks for is a red row, and one that keeps it *longer* an amber one.
388
+
389
+ Expiry on a versioned bucket only *hides* a dump; the rule's second clause purges the
390
+ hidden version `purge_days` later (default 1). That clause applies to every hidden
391
+ version however it got hidden - including dumps an attacker holding the backup
392
+ credential has deleted or overwritten - so it is also the window in which such an attack
393
+ can still be undone. Trading a few days of hourly retention for a longer window costs
394
+ about the same storage and buys a week to notice:
395
+
396
+ BACKUP_DB_TIERS = {'expire_days': {'hourly': 7}, 'purge_days': 7} # 7 visible + 7 hidden
397
+
398
+ The setup page generates the rules with that clause and flags a real rule that purges
399
+ sooner.
400
+
401
+ A deleted dump is loud - the status check sees it missing. An *overwritten* one is not:
402
+ the name, date and size still look right, and the real version sits hidden underneath
403
+ until the purge. So for tiered configs the status check also audits the bucket's
404
+ versions: dumps get unique names and are only ever hidden by expiry once they are
405
+ `expire_days` old, so a dump hidden younger than that, anything hidden under `monthly/`,
406
+ or a key holding two real versions is someone else's doing. The `Version audit` row
407
+ names them, says whether they are `hidden` (still recoverable), `overwritten` or already
408
+ `purged`, and gives the deadline the purge clock sets - run `backup_status` more often
409
+ than `purge_days`.
410
+
411
+ ### Explicit deletes with a locked archive
412
+
413
+ Lifecycle rules are only as durable as the bucket configuration - anyone with
414
+ `writeBuckets` can shorten them, and they delete silently. `delete: 'app'` moves the
415
+ deleting into the backup run, where it is logged and testable, and `lock_days` puts an
416
+ Object Lock retention on the tier that then has nothing else protecting it:
417
+
418
+ BACKUP_DB_TIERS = {
419
+ 'delete': 'app', # default: 'lifecycle'
420
+ 'expire_days': {'hourly': 15, 'daily': 91, 'monthly': None},
421
+ 'lock_days': {'monthly': 2557}, # 7 years, per object
422
+ 'lock_mode': 'COMPLIANCE', # or 'GOVERNANCE'
423
+ }
424
+
425
+ In this mode no lifecycle rules are generated or expected; the backup run deletes hourly
426
+ dumps older than `expire_days['hourly']` and daily ones older than `expire_days['daily']`,
427
+ straight after promoting - so a dump is only ever deleted once its daily copy exists.
428
+
429
+ Object Lock in B2 is **per object**, not per bucket: enabling it on the bucket only
430
+ permits objects to carry a retention date, and only the tiers in `lock_days` get one. So
431
+ the monthly archive becomes immutable while hourly and daily stay freely deletable in the
432
+ same bucket. `COMPLIANCE` cannot be shortened by anyone, including the account owner -
433
+ which is the point, and also means you are committed to paying for those objects for the
434
+ full period, and cannot delete the bucket while any remain. `GOVERNANCE` allows a key
435
+ with `bypassGovernance` to delete early.
436
+
437
+ The bucket needs Object Lock enabling, which `b2 bucket update --file-lock-enabled
438
+ <bucket>` does on an existing bucket - it cannot be turned off again. The key needs
439
+ `deleteFiles` and the file-retention capabilities; the setup page generates both, and adds
440
+ an **Archive lock** row that HEADs the newest monthly dump to prove it really carries a
441
+ retention date rather than trusting the settings.
442
+
443
+ The trade-off is explicit: the backup credential can now delete, which is what an attacker
444
+ would use it for. What survives that is exactly the tiers in `lock_days`.
445
+
446
+ ### Setting up the bucket
447
+
448
+ Since the package never creates a bucket or writes a lifecycle rule, the *Storage Setup*
449
+ tab on the backup page (`/backup/setup/`) works out what is missing and shows the
450
+ commands to fix it. It has one panel per `BACKUP_CONFIGS` entry - every destination at
451
+ once, rather than the one the other pages are on - and is strictly read-only: it checks
452
+ whether the bucket exists and reads the rules already on it, and changes nothing.
453
+
454
+ For a Backblaze destination it generates commands for the
455
+ [b2 command-line tool v4](https://b2-command-line-tool.readthedocs.io/):
456
+
457
+ b2 account authorize <accountKeyID> <applicationKey>
458
+ b2 bucket create --lifecycle-rule '{"fileNamePrefix": "django_backup/db/hourly/", "daysFromUploadingToHiding": 15, "daysFromHidingToDeleting": 1}' \
459
+ --lifecycle-rule '{"fileNamePrefix": "django_backup/db/daily/", "daysFromUploadingToHiding": 91, "daysFromHidingToDeleting": 1}' \
460
+ my-backups allPrivate
461
+ b2 key create --bucket my-backups --name-prefix django_backup/ django-cloud-backup-default-my-backups listBuckets,listFiles,readFiles,writeFiles
462
+ b2 bucket list
463
+
464
+ Points the page makes, and the reasons behind them:
465
+
466
+ - The first command needs an **account-level key** with `writeBuckets`,
467
+ `readBucketEncryption`, `writeBucketEncryption` and `writeBucketRetentions`. That is not
468
+ the key the application should use - the restricted key from `b2 key create` is, and the
469
+ page works its capabilities out from what the config actually does:
470
+
471
+ | capability | why | when |
472
+ |---|---|---|
473
+ | `listBuckets` | find the bucket; read its versioning, object-lock and lifecycle configuration (the checks on this page) | always |
474
+ | `listFiles` | list backups for the UI, dedup and pruning | always |
475
+ | `readFiles` | download for restore, and read metadata (md5, schema, ip, extensions) | always |
476
+ | `writeFiles` | upload backups, and server-side copies (tier promotion, `changed_files='history'`) | always |
477
+ | `readBuckets` | `Get Bucket Versioning` | always - read-only, for this page |
478
+ | `readBucketRetentions` | `Get Object Lock Configuration` | always - read-only, for this page |
479
+ | `readBucketLifecycleRules` | `Get Lifecycle Configuration` | always - read-only, for this page |
480
+ | `deleteFiles` | `BACKUP_DB_RETENTION` pruning deletes from the application | only when the config prunes; **never** with `db_tiers`, where the bucket does the deleting |
481
+ | `readFileRetentions`, `writeFileRetentions` | stamp Object Lock retention at upload and top it up with `extend_retention` | only when `lock` is set in `BACKUP_STORAGE` |
482
+
483
+ Everything else - `writeBuckets`, `deleteBuckets`, `writeKeys`, `bypassGovernance` - is
484
+ deliberately absent: a key that can undo the protection is not protection.
485
+ `--name-prefix` scopes the key to the backup root so it cannot touch anything else in
486
+ the bucket.
487
+
488
+ A `restore_only` config gets a different key entirely -
489
+ `listBuckets,listFiles,readFiles,readBuckets`, enough to find and download another
490
+ machine's backups and nothing more - and no bucket commands at all, since the bucket and
491
+ its lifecycle rules belong to the machine that writes them.
492
+
493
+ B2 gates each bucket read behind its own capability, and the three `readBucket*` ones
494
+ above exist only in the S3-compatible API - there is no B2 native equivalent, so they
495
+ are easy to miss. Without them the queries fail with `AccessDenied` and the page shows
496
+ `Unknown` rather than "not configured", which is why it names the missing capability in
497
+ the row. **A B2 key cannot be edited after creation** - to add a capability, create a
498
+ new key and update `BACKUP_STORAGE`.
499
+ - `b2 bucket update` **replaces the whole rule set**, so when the bucket already exists
500
+ the generated command carries the rules already on it as well. Rules that overlap a
501
+ tier prefix cannot be kept (B2 rejects overlapping rules) and are listed as removed.
502
+ If the existing rules could not be read, the page says so rather than handing over a
503
+ command that would quietly wipe them.
504
+ - `--file-lock-enabled` is never generated: a retention lock stops lifecycle expiry.
505
+ - `daysFromHidingToDeleting` is always set. B2 buckets keep versions, so expiry only
506
+ *hides* a file - without it the hidden version is kept and charged for forever. The
507
+ per-tier status row flags an existing rule that gets this wrong.
508
+ - A schema backed up separately needs its own pair of rules; the page adds them for the
509
+ schema folders it finds.
510
+ - Only b2 CLI v4 is supported. v3 (`create-bucket`, `--lifecycleRules`) is deliberately
511
+ not generated. AWS, R2, Azure and Drive destinations get a panel describing what to
512
+ create rather than commands.
513
+
514
+ A lifecycle rule is JSON, and every shell mangles it differently, so the panel has
515
+ **bash / PowerShell / cmd.exe** buttons that re-quote the commands - bash gets
516
+ `'{"fileNamePrefix": ...}'`, the Windows shells get `"{\"fileNamePrefix\": ...}"`, and
517
+ the PowerShell form carries the `--%` stop-parsing token because neither PowerShell 5.1
518
+ nor 7 passes a JSON argument to a native command unaltered. Copy the wrong one and b2
519
+ rejects the argument. The page starts on the shell your **browser's** platform suggests -
520
+ not the server's, since the page is usually served from a Linux container to a Windows
521
+ workstation and it is the workstation that runs b2. The management command takes
522
+ `--shell bash|powershell|cmd`, defaulting to the platform it runs on.
523
+
524
+ Each command has a clipboard button, plus a *Copy all* for the whole block. Copying uses
525
+ the browser's clipboard API, which only works over https or on localhost.
526
+
527
+ `python manage.py storage_setup [--config <name>]` prints the same thing on a server
528
+ with no web UI.
529
+
530
+ ## Client-side encryption
531
+
532
+ By default backups are stored as the provider receives them - anyone with access to
533
+ the Drive folder or bucket can read a full database dump. Setting `BACKUP_ENCRYPTION`
534
+ encrypts every backup (database dumps, local folder files and S3-source files) on the
535
+ client before upload, using chunked AES-256-GCM, so the provider only ever holds
536
+ ciphertext:
537
+
538
+ BACKUP_ENCRYPTION = True # reuse the encrypted-credentials SETTINGS_KEY
539
+ BACKUP_ENCRYPTION = '...' # or a dedicated urlsafe-base64 32-byte key
540
+
541
+ `True` derives backup keys from the same `SETTINGS_KEY` that already protects the
542
+ encrypted credentials - nothing new to manage, and the key never sits in the
543
+ repository. The trade-off is coupling: today `SETTINGS_KEY` can be rotated cheaply by
544
+ re-encrypting the `.enc` settings files, but once backups are encrypted with it, old
545
+ backups need the old key forever. A dedicated key avoids that; generate one with:
546
+
547
+ python -c "from encrypted_credentials.encrypted_file import random_key; print(random_key())"
548
+
549
+ and keep it in the encrypted private settings, not plain settings.py.
550
+
551
+ Notes:
552
+
553
+ - Restores are transparent - encrypted and older unencrypted backups are detected by
554
+ content and both restore normally, including `restore_db --local_file`. A wrong or
555
+ missing key fails cleanly before anything reaches `pg_restore`.
556
+ - **Losing the key means losing every backup encrypted with it.** Keep a copy of the
557
+ key somewhere that does not depend on the server or the backups themselves.
558
+ - File deduplication keeps working: the plaintext md5 is recorded in each file's
559
+ metadata at upload and compared on later runs. If you turn encryption off again,
560
+ already-encrypted file backups re-upload once (their metadata is no longer fetched).
561
+ - Database backups briefly need twice the dump size in `BACKUP_LOCAL_DB_DIR` while the
562
+ ciphertext copy is written; folder and S3-source backups encrypt in-stream with no
563
+ extra disk.
564
+ - Requires the `cryptography` package (`pip install django-cloud-backup[encryption]`) -
565
+ already present in practice, as encrypted-credentials depends on it.
566
+ - `BackupAzureToS3` is a separate rclone-compatible mirror and is not encrypted.
567
+ - With multiple backup configurations (below), encryption is set per config rather
568
+ than globally.
569
+
570
+ ## Multiple backup configurations
571
+
572
+ `BACKUP_CONFIGS` lets one project back up to several destinations with different
573
+ behaviour per destination - the classic case being a hardened offsite backup plus an
574
+ unencrypted database copy that a staging server restores from:
575
+
576
+ BACKUP_CONFIGS = {
577
+ 'default': {
578
+ 'storage': {'backend': 's3', 'bucket': 'offsite-backups', ..., 'lock': {...}},
579
+ 'encryption': True,
580
+ 'changed_files': 'protect',
581
+ },
582
+ 'staging': {
583
+ 'storage': {'backend': 's3', 'bucket': 'staging-transfer', ...},
584
+ 'encryption': False,
585
+ 'dirs': [], # database only, no folder backups
586
+ 'retention': [{'days': 1, 'number': 2}], # keep just the latest couple of dumps
587
+ 'changed_files': 'overwrite',
588
+ },
589
+ }
590
+
591
+ Config keys: `storage` (a `BACKUP_STORAGE`-style dict), `encryption`, `db` (include
592
+ the database, default True), `db_dir`, `dirs` (as `BACKUP_DIRS`), `azure_dirs` and
593
+ `azure_source` (as `AZURE_BACKUP_DIRS` / `AZURE_BACKUP_SOURCE`), `s3_dirs` (as
594
+ `S3_BACKUP_DIRS`), `retention`, `changed_files`, `db_tiers`, `restore_only` (read this
595
+ destination, never write to it - see *Live, staging and local machines* below).
596
+ **A key absent from a config
597
+ inherits the corresponding legacy global setting** (`BACKUP_STORAGE`,
598
+ `BACKUP_ENCRYPTION`, `BACKUP_DIRS`, ...), so shared values can stay in the globals -
599
+ but note that means a config without `'dirs': []` backs up the global `BACKUP_DIRS`.
600
+ Without `BACKUP_CONFIGS` the globals simply are the default config, so existing
601
+ installations are unaffected.
602
+
603
+ Running a config:
604
+
605
+ python manage.py backup_website --config staging
606
+ python manage.py restore_db --config staging # e.g. on the staging server
607
+
608
+ CELERY_BEAT_SCHEDULE = {
609
+ 'backup': {'task': 'cloud_backup.tasks.backup',
610
+ 'schedule': crontab(hour='8-19', minute=10)},
611
+ 'backup_staging': {'task': 'cloud_backup.tasks.backup',
612
+ 'schedule': crontab(hour=6, minute=0),
613
+ 'kwargs': {'config': 'staging'}},
614
+ }
615
+
616
+ The enhanced web UI shows a tab per destination - plus a *Storage Setup* tab, which is
617
+ how that page is reached - and everything on the page (the listings, the backup and
618
+ restore buttons, verify and empty trash) works on the selected destination. It opens on
619
+ the first config that includes the database, since a files-only destination has no
620
+ database page: that config's tab goes straight to its file browser instead. A destination whose settings do not resolve gets a warning tab
621
+ pointing at *Storage Setup*, which is the page that explains it. The selection is in
622
+ the url as `?config=<name>`, so a tab is bookmarkable. Un-parameterised tasks and the
623
+ basic (non-enhanced) UI still use the config named `'default'` - or the only entry, if
624
+ there is exactly one. Config names may contain any characters; the UI never puts the
625
+ name in a modal url.
626
+
627
+ Note that the file browser's directory index is per config: `/backup/files/0/` is the
628
+ first entry in *that* config's `dirs`.
629
+
630
+ For the staging pattern, the staging server's own
631
+ settings point a config at the same transfer bucket and `restore_db` pulls from it -
632
+ production never shares its offsite credentials or encryption key with staging. If
633
+ the transfer bucket holds an unencrypted production dump, treat the bucket itself as
634
+ production-sensitive, or give that config a dedicated key the staging server also
635
+ has.
636
+
637
+ Backups made by one config restore with that config's key: restoring an encrypted
638
+ backup through a config with a different key (or none) fails cleanly.
639
+
640
+
641
+ ### Live, staging and local machines
642
+
643
+ The usual three-role setup: one server produces the backups, and the others restore them
644
+ to get a copy of live data to work with.
645
+
646
+ | Role | Backs up | Restores | Backup root |
647
+ |---|---|---|---|
648
+ | Live | yes, on a schedule | no - web restore off | `backup/live` |
649
+ | Staging | occasionally, its own data | from live's dumps | `backup/staging` |
650
+ | Local machine | occasionally, its own data | from live's dumps | `backup/local` |
651
+
652
+ Staging never touches the live server: it reads live's dumps out of the bucket live backs
653
+ up to. That destination is marked **`'restore_only': True`**, which is what stops staging
654
+ writing into another machine's backups - every write refuses
655
+ (`RestoreOnlyConfig`), the web UI offers no backup, empty-trash or undelete action for it,
656
+ and *Storage Setup* generates a read-only key for it instead of the usual one. It is a
657
+ config setting rather than a matter of credentials because machines commonly share one
658
+ encrypted settings file, so the same credential is on all of them and only the config can
659
+ tell the roles apart.
660
+
661
+ # live/settings.py
662
+ BACKUP_ALLOW_RESTORE = False # also the default once DEBUG is off
663
+ BACKUP_ENCRYPTION = True
664
+ BACKUP_STORAGE = {'backend': 's3', 'b2': True, 'bucket': 'my-backups',
665
+ 'access_key_id': access_key_id, 'secret_key': secret_key,
666
+ 'root': 'backup/live'}
667
+ BACKUP_DIRS = [(MEDIA_ROOT, 'media')]
668
+
669
+ # staging/settings.py - the local machine is the same with root 'backup/local'
670
+ BACKUP_ALLOW_RESTORE = True # restore from the management page
671
+ BACKUP_ENCRYPTION = True # the shared settings key, so live's dumps decrypt
672
+ BACKUP_STORAGE = {...as above...}
673
+ BACKUP_CONFIGS = {
674
+ 'default': {'storage': dict(BACKUP_STORAGE, root='backup/staging')},
675
+ 'live': {'storage': dict(BACKUP_STORAGE, root='backup/live'),
676
+ 'restore_only': True,
677
+ 'dirs': [], 's3_dirs': []}, # the database is what gets restored
678
+ }
679
+
680
+ Restoring live's latest dump on staging:
681
+
682
+ python manage.py restore_db --config live
683
+
684
+ or from the management page: pick the *live* tab and use **Drop Restore** on a dump.
685
+
686
+ Points worth getting right:
687
+
688
+ - **Give each role its own `root`.** Pruning is scoped to the machine's own public IP so
689
+ servers do not delete each other's dumps, but `db_tiers` promotion has no such filter -
690
+ a staging dump written into live's prefix would be promoted into live's monthly archive.
691
+ Separate roots keep each machine's retention entirely its own.
692
+ - **`BACKUP_ALLOW_RESTORE` off on live**, which is what it already is once `DEBUG` is off.
693
+ It is enforced server-side on every web restore endpoint. `manage.py restore_db` is not
694
+ affected by it, so disaster recovery on live stays possible from the command line.
695
+ - **Never schedule `cloud_backup.tasks.backup` with `kwargs={'config': 'live'}`** anywhere
696
+ but live. It would refuse anyway, but a beat schedule that raises every night is noise.
697
+ - The same encrypted settings file on every machine means `BACKUP_ENCRYPTION = True`
698
+ derives the same key everywhere, so staging can decrypt live's dumps with nothing extra
699
+ to configure. If the machines do **not** share settings, either give the restore_only
700
+ config live's key explicitly, or have live write a second, unencrypted copy to a
701
+ transfer bucket that staging reads (the *Multiple backup configurations* example above).
702
+ - Restoring writes to `DATABASES['default']` of the machine doing the restoring - the
703
+ config picks which dumps to read, never where they land.
704
+
705
+ If a machine only ever restores and backs nothing up at all, `BACKUP_RESTORE_ONLY = True`
706
+ sets the flag globally without needing `BACKUP_CONFIGS`.
707
+
708
+
709
+ ## Management commands
710
+
711
+ python manage.py backup_website
712
+ python manage.py restore_db
713
+ python manage.py storage_setup
714
+
715
+ ## Management page
716
+
717
+ urls.py
718
+
719
+ urlpatterns = [
720
+ path('backup/', include('cloud_backup.urls')),
721
+ ....
722
+
723
+
724
+ All URL names live under the `cloud_backup` namespace (e.g.
725
+ `reverse('cloud_backup:backup-info')`). Previously the basic management page
726
+ used un-namespaced names such as `backup-info`; add the `cloud_backup:` prefix
727
+ if you reverse them yourself.
728
+
729
+ An enhanced version of the management page will be shown if the following django apps are installed
730
+
731
+ 'django_modals', 'django_datatables', 'django_menus', 'ajax_helpers'
732
+
733
+ from the following PyPi packages
734
+
735
+ django-nested-modals, django-filtered-datatables, django-tab-menus, django-ajax-helpers
736
+
737
+ ### Branding the management page
738
+
739
+ The enhanced page views build the whole UI (menus, storage info and tables) into a
740
+ single HTML string, `{{ backup_content }}`, so it can be dropped into your own
741
+ template. Subclass the base views and set `template_name`:
742
+
743
+ from cloud_backup.enhanced_views import (BackupBaseView, BackupFilesBaseView,
744
+ SchemaTableBaseView, StorageSetupBaseView)
745
+
746
+ class MyBackupView(BackupBaseView):
747
+ template_name = 'myapp/backup.html'
748
+
749
+ class MySchemaTableView(SchemaTableBaseView):
750
+ template_name = 'myapp/backup.html'
751
+
752
+ class MyBackupFilesView(BackupFilesBaseView):
753
+ template_name = 'myapp/backup.html'
754
+
755
+ class MyStorageSetupView(StorageSetupBaseView):
756
+ template_name = 'myapp/backup.html'
757
+
758
+ The template must include the ajax_helpers/datatables/modals libraries and the
759
+ page script, then place the content wherever it fits your layout:
760
+
761
+ {% load ajax_helpers %}
762
+ {% lib_include 'ajax_helpers' 'Bootstrap' 'FontAwesome' module='ajax_helpers.includes' %}
763
+ {% lib_include 'datatable' module='django_datatables.includes' %}
764
+ {% lib_include 'Modals' module='django_modals.includes' %}
765
+ {{ ajax_helpers_script }}
766
+ ...
767
+ {{ backup_content }}
768
+
769
+ Register the subclasses with `backup_urlpatterns` so the menu links and modals
770
+ (which reverse the standard `cloud_backup:` URL names) point at your views:
771
+
772
+ from cloud_backup.urls import backup_urlpatterns
773
+
774
+ urlpatterns = [
775
+ path('backup/', include((backup_urlpatterns(
776
+ backup_view=MyBackupView, schema_table_view=MySchemaTableView,
777
+ files_view=MyBackupFilesView, setup_view=MyStorageSetupView), 'cloud_backup'))),
778
+ ]
779
+
780
+ The unbranded standard page remains the default when using
781
+ `include('cloud_backup.urls')`.
782
+
783
+ ### Restoring from the management page
784
+
785
+ Restore and drop-schema actions on the enhanced management page require
786
+
787
+ BACKUP_ALLOW_RESTORE = True
788
+
789
+ which defaults to the value of `DEBUG`. This is enforced server-side on every
790
+ restore endpoint (not just by hiding the buttons), so a production server with
791
+ `DEBUG = False` and no `BACKUP_ALLOW_RESTORE` setting cannot be restored from
792
+ the web UI even by a superuser. Set `BACKUP_ALLOW_RESTORE = True` on staging and
793
+ development machines where restoring is wanted. The `manage.py restore_db`
794
+ command is not affected by this setting, so disaster recovery on a live server
795
+ remains possible from the command line.
796
+
797
+ ## Browsing and verifying folder backups
798
+
799
+ When `BACKUP_DIRS`, `AZURE_BACKUP_DIRS` (or `S3_BACKUP_DIRS`) is configured, the
800
+ enhanced management page shows a `Backup Files` button that backs up all configured
801
+ folders without touching the database, and a single `Files` button opening a file
802
+ browser. Its root level lists each configured backup directory as a folder (a cloud
803
+ icon marks an Azure source); clicking through navigates the backed-up tree one level
804
+ at a time (with breadcrumbs back up), and files show their size, backup date and
805
+ checksum - the plaintext md5 recorded with the file at upload time (so it stays
806
+ comparable when client-side encryption is enabled).
807
+
808
+ The `Verify` button on each row re-hashes the file on the server's local disk
809
+ (or, for an Azure source, reads the blob's current md5/etag) and compares it with
810
+ what was recorded at backup time, reporting:
811
+
812
+ - `Match` - the source file is identical to its backup
813
+ - `Changed` - the source file no longer matches its backup
814
+ - `Missing locally` / `Missing from Azure` - the source file has been deleted since
815
+ it was backed up
816
+ - `No stored checksum` - the backup has no comparable checksum (e.g. a large
817
+ multipart S3 upload made without md5 metadata)
818
+
819
+ `Verify All Files` runs the same comparison over the whole directory as a
820
+ celery task (the worker must be running) and reports a summary.
821
+
822
+ The browser carries the same backup buttons as the management page, so a
823
+ destination that has no database page - a config with `db` off, whose tab opens
824
+ the browser - can still be backed up from the web UI. Its root listing has
825
+ `Backup Files`, and inside one directory there is a `Backup <directory>` button
826
+ that backs up just that folder source (the whole directory, not the sub-folder
827
+ being browsed). The equivalent on the command line is
828
+ `backup_website --folders_only --backup_dir <index>`, where the index counts
829
+ `BACKUP_DIRS` entries first and then `AZURE_BACKUP_DIRS`.
830
+
831
+ The browser and verification are read-only and require the same `access_admin`
832
+ permission as the rest of the management page; the backup buttons, like every
833
+ other backup button, require a superuser. Note that on an S3-compatible
834
+ destination with client-side encryption enabled, listing the checksums costs one
835
+ metadata request per file, so the page can be slow to load for very large trees.
836
+
837
+ ## Configure Azure folder backups
838
+
839
+ Media that django-storages keeps in Azure Blob Storage has no local directory for
840
+ `BACKUP_DIRS` to back up. `AZURE_BACKUP_DIRS` names prefixes ("folders") in the
841
+ container instead, and they are backed up through exactly the same pipeline as a local
842
+ directory: the same destination folders (so `media` below appears in the file browser
843
+ just as a local `media` would), client-side encryption, `BACKUP_CHANGED_FILES`
844
+ protection, object lock and per-file verification. Requires
845
+ `pip install django-cloud-backup[azure]`.
846
+
847
+ settings.py
848
+
849
+ # (blob prefix, destination folder). The prefix has no trailing slash and is
850
+ # relative to the container - include django-storages' `location` if one is set.
851
+ # '' is the whole container.
852
+ AZURE_BACKUP_DIRS = [('media', 'media')]
853
+
854
+ When the project's default file storage is django-storages' `AzureStorage`, its
855
+ container and credentials (the `STORAGES['default']['OPTIONS']` or `AZURE_*`
856
+ settings) are used and nothing else is needed. To back up some other container, or
857
+ when the default storage is not Azure, say which:
858
+
859
+ AZURE_BACKUP_SOURCE = {'container': 'media', 'connection_string': connection_string}
860
+ # or {'container': 'media', 'account_url': 'https://<account>.blob.core.windows.net',
861
+ # 'credential': account_key_or_sas_token}
862
+
863
+ Both are available per config as `azure_dirs` / `azure_source`. Nothing is downloaded
864
+ to decide what needs backing up: a blob is skipped when its md5 (which Azure records
865
+ for single-request uploads - django-storages' normal case) or otherwise its etag
866
+ matches what was stored with the backup, so an unchanged blob costs one listing entry
867
+ and a changed one is re-uploaded. The destination is listed once, recursively, rather
868
+ than folder by folder, and its stored metadata - a request per object on S3-compatible
869
+ storage - is only read for the files the listing cannot settle by hash (blobs Azure holds
870
+ no md5 for, encrypted copies, and anything that has actually changed), so a nightly run
871
+ over a large, mostly unchanged container is a couple of listings and a few requests, not
872
+ one per file. The `backup_azure_s3.BackupAzureToS3` class is
873
+ different: a standalone rclone-compatible mirror that bypasses this pipeline.
874
+
875
+ ## Configure S3 folder backups
876
+
877
+ settings.py
878
+
879
+ AWS_ACCESS_KEY_ID = id
880
+ AWS_SECRET_ACCESS_KEY = key
881
+ AWS_PRIVATE_STORAGE_BUCKET_NAME = bucket
882
+
883
+ S3_BACKUP_DIRS = [('S3-source-folder1', 'google-drive-folder1'),
884
+ ('S3-source-folder2', 'google-drive-folder2')
885
+ ]
886
+
887
+ ## Configure cleaning of old datatabase backups
888
+
889
+ settings.py
890
+
891
+ BACKUP_DB_RETENTION = [{'hours': 1, 'number': 4},
892
+ {'hours': 2, 'number': 10},
893
+ {'days': 1, 'number': 10},
894
+ {'months': 1, 'number': 36},
895
+ ]
896
+
897
+ Each entry keeps the newest dump in each period for that many periods, and everything
898
+ not kept by some entry is deleted after each backup. On an S3-compatible destination
899
+ `BACKUP_DB_TIERS` (above) is the alternative: the bucket's lifecycle rules do the
900
+ deleting instead, and the application never needs delete permission.
901
+
902
+
903
+ ## Schedule backup with celery beat
904
+
905
+ CELERY_BEAT_SCHEDULE = {
906
+ 'backup': {
907
+ 'task': 'cloud_backup.tasks.backup',
908
+ 'schedule': crontab(hour='8-19', minute=10, day_of_week='mon-fri')
909
+ }
910
+ }
911
+
912
+
913
+ ## Checking that the backups are current
914
+
915
+ Error tracking only tells you about a backup that ran and *failed*. A celery beat that has
916
+ stopped, or a worker that never picks the task up, raises nothing anywhere - so the package
917
+ answers the positive question itself. Every run of `backup`, `promote_db_tiers` and
918
+ `extend_retention` is recorded in the database (`BackupRun`; rows are pruned after
919
+ `BACKUP_RUN_HISTORY_DAYS`, default 90), and the status check lists what is actually at each
920
+ destination and grades it against your beat schedule:
921
+
922
+ python manage.py backup_status # every config; exit code 1 if anything is not OK
923
+ python manage.py backup_status --json
924
+
925
+ OK database: Latest database dump Sat 29 Aug 09:50 (27 min ago), 285.8 MiB [older than the 09:50 run]
926
+ OK database: Dump size vs previous 285.8 MiB vs 285.8 MiB (100%) [< 80% of previous]
927
+ OK database: Latest daily copy Fri 28 Aug, 285.8 MiB [before Fri 28 Aug]
928
+ OK database: Latest monthly copy Jul 2026, 280.1 MiB [before Jul 2026]
929
+ OK database: Version audit nothing unexplained - 9 hidden by expiry, 214 entries listed [any hidden version or overwrite the retention policy does not explain]
930
+ OK database: Backup run succeeded Sat 29 Aug 09:51 (26 min ago) [older than the 09:50 run]
931
+ OK database: Tier promotion run succeeded Sat 29 Aug 06:00 (4 h 17 min ago) [older than the 06:00 run]
932
+ OK files: Destination reachable unity-backup is accessible [not accessible]
933
+ OK files: Backup run succeeded Sat 29 Aug 01:31 (8 h 46 min ago) [older than the 01:30 run]
934
+
935
+ The same rows are served as json at `backup/status/` (`?config=<name>` to limit it,
936
+ `?refresh=1` to bypass the five-minute cache) for a monitoring agent to read. The view
937
+ only admits a superuser or the backup permission; subclass `cloud_backup.views
938
+ .BackupStatusView`, override `has_permission(request)` to accept your monitor's credential,
939
+ and pass it as `backup_urlpatterns(status_view=...)`.
940
+
941
+ Rows are graded against the `crontab` entries in `CELERY_BEAT_SCHEDULE` for the config
942
+ (a run is late once `grace_minutes` past its slot, counting only the days the crontab
943
+ fires - a `mon-fri` schedule is not stale over the weekend), or by plain age
944
+ (`max_age_hours`) on a server where the task is not scheduled.
945
+
946
+ The run history behind those rows is browsable too: the enhanced UI has a Run Log page
947
+ at `backup/runs/` (a button on each destination's page), and `BackupRun` is registered
948
+ read-only in the Django admin for projects on the basic UI. A dump smaller than `size_drop` of the one before it
949
+ is flagged, and with `BACKUP_DB_TIERS` the daily and monthly copies must be there by
950
+ `promotion_deadline`. The defaults are in `cloud_backup.config.DEFAULT_STATUS`; override
951
+ them for every config with `BACKUP_STATUS = {...}` or per config with a `'status': {...}` key.
952
+
953
+ ## Migrating from django-gdrive-backup
954
+
955
+ This package was previously published as `django-gdrive-backup`. The rename is a breaking
956
+ release; upgrading requires the following changes in your project:
957
+
958
+ - Install `django-cloud-backup` (and its extras, e.g. `django-cloud-backup[s3]`) instead of
959
+ `django-gdrive-backup`
960
+ - `INSTALLED_APPS`: `'gdrive_backup'` → `'cloud_backup'`
961
+ - urls.py: `include('gdrive_backup.urls')` → `include('cloud_backup.urls')`, and any
962
+ reverses/`{% url %}` tags use the `cloud_backup:` namespace instead of `gdrive_backup:`
963
+ - Celery beat schedules: task names are now `cloud_backup.tasks.*`
964
+ (e.g. `cloud_backup.tasks.backup`)
965
+ - Settings renamed: `BACKUP_GDRIVE_DIR` → `BACKUP_ROOT`, `BACKUP_GDRIVE_DB` → `BACKUP_DB_DIR`
966
+ (they apply to every destination backend, not just Google Drive). `BACKUP_TEAM_DRIVE` is
967
+ unchanged.
968
+ - Removed legacy method aliases `backup_db_gdrive`, `restore_gdrive_db` and
969
+ `restore_gdrive_folder` - use `backup_db_to_storage`, `restore_db_from_storage` and
970
+ `restore_folder`
971
+ - Client-side encryption: the file format constants changed with the rename, so files
972
+ encrypted by pre-release versions of the encryption feature cannot be read. No published
973
+ release included encryption, so this affects no production backups.
974
+
975
+ Backups already in your storage destination are unaffected - folder layout and metadata
976
+ are unchanged, and existing backups restore as before.