How can I connect backblaze b2 bucket to a django project to store media and static files?

334 Views Asked by At

I want to shift from AWS to Backblaze, I tried to follow the documentation on django storages to simply modify a little my already exisiting aws configuration but I just kept having errors. My current aws configuration is like this:

   AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY')
   AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY')
   AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME')
   AWS_DEFAULT_ACL = None
   AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'
   AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'}
   DEFAULT_FILE_STORAGE = 'myproject.storages.MediaStorage'

   AWS_QUERYSTRING_AUTH = False

   STATIC_LOCATION = 'static'
   STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{STATIC_LOCATION}/'
   STATICFILES_STORAGE = 'myproject.storages.StaticStorage'

   MEDIA_LOCATION = 'media'
   MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{MEDIA_LOCATION}/'
   DEFAULT_FILE_STORAGE = 'myproject.storages.MediaStorage'
1

There are 1 best solutions below

3
metadaddy On

I got this working a little while ago. My complete sample app is at https://github.com/backblaze-b2-samples/django-storages-backblaze-b2/tree/main/b2-example-static-and-media.

There are also samples for the 'static only' and 'public and private' in the same repository.

Here are the settings I used:

AWS_ACCESS_KEY_ID = '<your b2 application key id>'
AWS_SECRET_ACCESS_KEY = '<your b2 application key>'

AWS_STORAGE_BUCKET_NAME = '<a public bucket>'

AWS_S3_REGION_NAME = '<your b2 region - e.g. us-west-001>'
AWS_S3_ENDPOINT = f's3.{AWS_S3_REGION_NAME}.backblazeb2.com'
AWS_S3_ENDPOINT_URL = f'https://{AWS_S3_ENDPOINT}'

AWS_S3_OBJECT_PARAMETERS = {
    'CacheControl': 'max-age=86400',
}

AWS_LOCATION = 'static'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATIC_URL = f"https://{AWS_STORAGE_BUCKET_NAME}.{AWS_S3_ENDPOINT}/"

DEFAULT_FILE_STORAGE = 'mysite.storage_backends.MediaStorage'

The critical settings you might be wrestling with are AWS_S3_REGION_NAME, AWS_S3_ENDPOINT and AWS_S3_ENDPOINT_URL, as these are all different from the AWS defaults. If you follow my settings, you just need to set AWS_S3_REGION_NAME; the remaining items will be set automatically.

I don't think you need to set AWS_S3_CUSTOM_DOMAIN unless you are using a CDN.

If the above doesn't help, please edit your question to include the B2 settings you tried and the errors you saw.