Package: django-backblaze-b2
django-backblaze-b2A storage backend for Django that usesBackblaze's B2 APIs.Implementation wrapsOfficial Python SDKChangelog / ReleasesSeehttps://github.com/ehossack/django-backblaze-b2/releasesHow to useInstall from this repo, or install from PyPi:pip install django-backblaze-b2As tested, requires python 3.7 or greater but solely due to type annotations. PRs welcome :)Configure your djangosettings. A minimalistic config would be:CACHES={"default":....,# add a cache via db table or memcached that can be accessed from multiple threads"django-backblaze-b2":{'BACKEND':'django.core.cache.backends.db.DatabaseCache','LOCATION':'django_backblaze_b2_cache_table',}}BACKBLAZE_CONFIG={# however you want to securely retrieve these values"application_key_id":os.getenv("BACKBLAZE_KEY_ID"),"application_key":os.getenv("BACKBLAZE_KEY"),}Theoretically you may now refer to the base storage class as a storage class (see the sample app for some usage: you can run withmake run-sample-projalthough you might want to configure theSECONDS_TO_RUN_APPvariable insettings.envto be 0 for unlimited to try things out)
e.g.fromdjango_backblaze_b2importBackblazeB2StorageclassMyModel(models.Model):file_field=models.FileField(upload_to="uploads",storage=BackblazeB2Storage)Public/Logged-In/Private storageAdddjango_backblaze_b2to yourINSTALLED_APPSAdd the urls to yoururlpatternsin the rooturls.py:urlpatterns=[...path('',include('django_backblaze_b2.urls')),]CachingTo retrieve file metadata ("file info" as the b2 sdk names it), this library has to authorize and request data from b2 servers, even for just resolving the url for a file. Because these are network calls, and relatively expensive in comparison to a file-based storage, and because data is unlikely to change frequently, there is some caching done by this library.By default, the account information (account_info) configuration of the settings uses a cache by the name ofdjango-backblaze-b2which you must have in yourCACHESsection of yoursettings.py. This is to leverage django's thread-safe cache implementations, and if you are using a database cache table or memcached, (rather than LocMemCache) your cache can be shared by the multiple django processes that typically serve requests.It is not recommended configureaccount_infowith thedefaultdjango cache, as theclear()method may be called during the backblaze lifecycle.If you do not wish to use a django cache, you can use a sqlite database on disk for caching, or use a non-thread-safe in-memory implementation. This is only recommended for single-threaded deployments (remember in most deployments a new thread serves each request).For further discussion on this seehttps://github.com/ehossack/django-backblaze-b2/issues/16ConfigurationsYou may want to use your own bucket name, or set further configuration such as lazy authorization/validation, or specifying file metadata.Refer tothe optionsfor all options.You can modify the settings dict, but additionally override any setting with theoptskeyword argument to the storage classes.To specify different buckets to use for your public, logged-in, staff storage, you can set thespecificBucketNamesattribute of the settings dict.WhyThere are several Django storage packages out there already which support B2, but none met my needs. These are:django-storagesLarge community engagement ✅Well-tested ✅Second-class supportviaApache Libcloud❌Disconnect in configuration and actual use ❌PR list with low turnaround ❌django-b2Similar aim to this project, around official backblaze SDK ✅Mixed goals (storage, scripts) ❌Tests?? ❌django-backblazeb2-storageSimple configuration ✅Not based around python SDK (potentially harder to keep up with version changes) ❌Tests?? ❌S3 Compatible APIBackblazed can be used with anS3-compatible APIThis is great, but most packages use an older version of the S3 Api (v2). Backblaze uses v4.What this package offersType AnnotationsTestedNo hacks required to get up and running around API deficiencies (any hacks are not exposed in API)Support for public/private files, restricted via Django user permissionsSupport for CDN and cached url detailsHow it worksA simple implementation of thedjango.core.files.storage.Storageclass provides handling for storage behaviour within your Django applicationThree url routes are appended to the root of your application:/b2//b2l//b2s/These routes act as a proxy/intermediary between the requester and backblaze b2 apis. The public/b2/allows exposing files from a private bucket, and the logged-in and staff routes will perform the known validations of a django app to prevent unauthorized access.If you use a CDN config, you can specify the CDN options and then include the bucket url segments (/file/<bucket-name>/) if your CDN is proxying the classic b2 url (e.g.f000.backblazeb2.com) or not, if you are proxying the s3-compatible url.GotchasThe original filename + any upload paths is stored in the database. Thus your column name must be of sufficient length to hold that (unchanged behaviour fromFileSystemStorage)When retrieving files from thePublicStorage,LoggedInStorageorStaffStorage, you may not override the"bucket"or authorization options, or else when the app proxies the file download, it will be unable to retrieve the file from the respective bucket.Simply usingLoggedInStorageorStaffStorageis not enough to protect your files if your bucket is not public. If any individual gains access to the file ids/urls for these files, there is no authentication around them. It is up to the implementer to ensure the security of their application.Once the file is uploaded, and someone obtains a file url (e.g.http://djangodomain.com/b2l/uploads/image.png), the django model is no longer involved in file resolution. This means that if you share the bucket between multiple use-cases, you could in theory find files that don't belong to your django app (e.g. some image2.png), or similarly if you delete/change your models, the files could still be downloaded. Consider using an app likedjango-cleanupif this is important to youContributingContributions welcome!Please ensure test coverage does not decrease in a meaningful way.Ensure formatting is compliant (make lint)Useconventional commitsSetting up for developmentRequirespythonpyenv - align local versionGNU Make(optional) docker - run sample appVersion compatibility reminderlinkVerStatusEOL3.12bugfix2028-103.11bugfix2027-103.10security2026-103.9security2025-103.8security2024-10Runningmake setupYou can run django withmake run-djangoto test django app.You can run tests withmake testYou can view test coverage withmake test-coverage, then see in the terminal,
opentest/htmlcov/index.htmlor usecov.xmlin your favourite IDE like VSCodeReleasingmake releaseCleanupmake cleanup