Back ups
1. What is django-dbbackup?
django-dbbackup is a Django application designed to: 1. Back up your database (and optionally media files). 2. Restore your database from these backups. 3. Store backups locally or remotely (e.g., Amazon S3, Dropbox, etc.).
It integrates with Django’s settings and management commands, making it straightforward to schedule or invoke backups from the command line or cron jobs.
- GitHub Repo: django-dbbackup
- PyPI: django-dbbackup
2. Installation
Install via pip:
pip install django-dbbackup
Add to Installed Apps:
= [ INSTALLED_APPS ...'dbbackup', # django-dbbackup ]
Migrate (if any model changes):
python manage.py migrate
3. Basic Configuration in settings.py
A minimal setup might look like this:
# settings.py
# Add dbbackup to installed apps (already done above)
= [
INSTALLED_APPS
...,'dbbackup',
]
# DBBACKUP configuration
# Where to store backup files.
# "filesystem": store in local file system
# "s3": store on Amazon S3
= 'django.core.files.storage.FileSystemStorage'
DBBACKUP_STORAGE = {
DBBACKUP_STORAGE_OPTIONS 'location': '/path/to/backups/', # e.g. "/var/backups/myproject"
}
# (Optional) Compress backups
= True
DBBACKUP_COMPRESS
# (Optional) Encrypt backups using GPG
= None DBBACKUP_GPG_RECIPIENT
3.1 Key Settings
DBBACKUP_STORAGE
: Defines the storage class used to store backup files.- Common values:
django.core.files.storage.FileSystemStorage
for local backups.storages.backends.s3boto3.S3Boto3Storage
for S3 backups (requiresdjango-storages
).
- Common values:
DBBACKUP_STORAGE_OPTIONS
: A dictionary of options passed to your storage class.- For local file system:
{'location': '/path/to/backups/'}
. - For S3:
{'access_key': '...', 'secret_key': '...', 'bucket_name': 'my-backups'}
.
- For local file system:
DBBACKUP_FILENAME_TEMPLATE
(Optional): Custom filename format for backups, e.g.,"{datetime}-{databasename}.{extension}"
.DBBACKUP_CLEANUP_KEEP
andDBBACKUP_CLEANUP_KEEP_MEDIA
(Optional): Number of backups to keep if you use thecleanup
command.DBBACKUP_COMPRESS
(Boolean): IfTrue
, compresses backup files (default isFalse
).Encryption: If you want GPG encryption, set
DBBACKUP_GPG_RECIPIENT = 'my-gpg-id'
.
4. Usage and Commands
4.1 Create a Database Backup
python manage.py dbbackup
- This command creates a backup of your default database and saves it to the configured storage.
- By default, it also backs up all configured databases in
settings.DATABASES
unless you specify--database
.
Key Options: - --database <alias>
: Backup a specific DB alias. - --compress
: Override the default compress setting. - --encrypt
: Override the default GPG encrypt setting. - --output
or -o
: Writes the backup to a local file (e.g., dbbackup -o /tmp/mydbbackup
).
Example:
python manage.py dbbackup --database default --compress --encrypt
4.2 Restore a Database Backup
python manage.py dbrestore
By default, this looks for the latest backup file in the configured storage and restores it.
Key Options: - --database <alias>
: Restore a specific DB. - --input <filename>
or -i
: Restore from a specific backup file. - --noinput
: Skip “Are you sure?” prompts. - --decrypt
: Decrypt if needed.
Example:
python manage.py dbrestore --database default -i /path/to/backups/2023-01-20-default.gz --noinput
4.3 Backing Up Media Files
django-dbbackup can back up your MEDIA_ROOT
with:
python manage.py mediabackup
And restore media:
python manage.py mediarestore
Ensure you have the relevant storage configured if you want media backups stored similarly (same or different location).
4.4 Cleanup Old Backups
To automatically remove older backups (beyond a certain number): 1. Set DBBACKUP_CLEANUP_KEEP = <int>
in settings. 2. Run: bash python manage.py dbbackup_cleanup
or bash python manage.py mediabackup_cleanup
5. Common Storage Options
5.1 Local Filesystem
Set:
= 'django.core.files.storage.FileSystemStorage'
DBBACKUP_STORAGE = {
DBBACKUP_STORAGE_OPTIONS 'location': '/path/to/backups/',
}
Make sure /path/to/backups/
is writable by Django.
5.2 Amazon S3
You can use django-storages: 1. Install: bash pip install django-storages boto3
2. Configure S3 in settings.py
: python DBBACKUP_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DBBACKUP_STORAGE_OPTIONS = { 'access_key': 'YOUR_ACCESS_KEY', 'secret_key': 'YOUR_SECRET_KEY', 'bucket_name': 'my-backups-bucket', }
3. Alternatively, if you already have a custom storage class for S3, point DBBACKUP_STORAGE
to that class.
5.3 Other Storage
- Dropbox: There are examples of custom Dropbox storages or
django-storages
integration. - FTP / SFTP: Use a custom storage or library that integrates with ftp/sftp.
6. Scheduling Backups
Typically, you schedule backups with cron or a job scheduler like celery beat or systemd timers. For example, a cron job to back up the DB daily at midnight:
0 0 * * * /path/to/venv/bin/python /path/to/project/manage.py dbbackup --compress --encrypt
You can similarly schedule media backups or calls to dbbackup_cleanup
.
7. Security Considerations
- Encryption (GPG):
- If you store backups in a remote location or want extra security, set
DBBACKUP_GPG_RECIPIENT
so that backups are encrypted at rest. - You’ll need GPG installed and a matching key.
- If you store backups in a remote location or want extra security, set
- Permissions:
- Ensure backup directories and keys are protected so only authorized users can read them.
- Handling Secrets:
- Do not commit your DB or storage credentials in version control. Use environment variables or a secrets manager.
8. Debugging & Common Issues
- File Permissions:
- Make sure Django can write to
DBBACKUP_STORAGE_OPTIONS['location']
if using local storage.
- Make sure Django can write to
- Missing or Wrong Database Dumps:
- Check that your
DATABASES
config has the correct engine. For example, if using Postgres, ensure thepg_dump
utility is installed and inPATH
.
- Check that your
- S3 Access Denied:
- Double-check your AWS credentials and bucket permissions.
9. Additional Features & Tips
- Partial Database Backup: Not supported out of the box, dbbackup typically dumps the entire DB.
- Multiple DBs:
- If you have more than one database in
settings.DATABASES
,dbbackup
will back them all up by default, naming them accordingly. Use--database
to target one.
- If you have more than one database in
- Versioning: If storing backups on S3, you can enable versioning on the bucket for extra safety (though this is outside django-dbbackup’s scope).
- Notifications: You might integrate Slack or email notifications to confirm successful backups or handle errors.
10. Example End-to-End Setup
settings.py
:
= [
INSTALLED_APPS
...,'dbbackup',
]
= 'storages.backends.s3boto3.S3Boto3Storage'
DBBACKUP_STORAGE = {
DBBACKUP_STORAGE_OPTIONS 'access_key': os.getenv('AWS_ACCESS_KEY_ID'),
'secret_key': os.getenv('AWS_SECRET_ACCESS_KEY'),
'bucket_name': 'myproject-dbbackups',
}= 5
DBBACKUP_CLEANUP_KEEP = True
DBBACKUP_COMPRESS = 'my_gpg_key@example.com' # If you want encryption DBBACKUP_GPG_RECIPIENT
Crontab entry (runs daily at 2am):
0 2 * * * /path/to/venv/bin/python /path/to/project/manage.py dbbackup_cleanup && \
/path/to/venv/bin/python /path/to/project/manage.py dbbackup --clean --compress --encrypt
--clean
triggers cleanup after backup, but you can also rundbbackup_cleanup
separately.
Command line usage to restore the latest backup:
python manage.py dbrestore --noinput --decrypt
Summary
- Install
django-dbbackup
, configure it insettings.py
. - Choose storage (local or remote).
- Run commands (
dbbackup
,dbrestore
,mediabackup
, etc.) from the CLI or a scheduler. - Optional enhancements: GPG encryption, compression, and cleanup for old backups.
- Test your backup and restore procedure regularly to ensure your data can be recovered when needed.
With these steps, you’ll have a robust backup and restore process in place for your Django project using django-dbbackup.