Skip to content

Instantly share code, notes, and snippets.

@fronbasal
Last active July 5, 2024 22:58
Show Gist options
  • Save fronbasal/c87f35b099290bc28f28e3b7c375f079 to your computer and use it in GitHub Desktop.
Save fronbasal/c87f35b099290bc28f28e3b7c375f079 to your computer and use it in GitHub Desktop.
Pretix django-storages (S3) configuration for staticfiles & media

Pretix django-storages (S3) configuration

This is a quick write-up on how to configure Pretix (based on the Small-scale manual deployment documentation by Pretix) to use S3 (or another supported django-storages backend) to speed up page hits.

The process of this and additional steps to undertake are underlined in Pretix' scaling guide.

I wrote this to make it easier for myself and you to do this again ;)

  1. Create a new directory in /var/pretix, i.e. settings, include this directory in your PYTHONPATH.
  2. Add a custom settings.py by overwriting DJANGO_SETTINGS_MODULE as outlined in the scaling guide
  3. Add a custom cached-storage variant that also stores files locally for django-compressor.

Use the default settings.py from the pretix repo as the base for your settings.py. You can append the following (this will set this for static and media files, read carefully and adjust as needed):

COMPRESS_STORAGE = "yourmodule.storage.CachedS3Storage"
STORAGES["default"]["BACKEND"] = STORAGES["staticfiles"]["BACKEND"] = COMPRESS_OFFLINE_MANIFEST_STORAGE = COMPRESS_STORAGE
COMPRESS_ROOT = STATIC_ROOT
STATIC_URL = COMPRESS_URL = "https://cdn.example.com/"
AWS_S3_CUSTOM_DOMAIN = "cdn.example.com"
AWS_ACCESS_KEY_ID = ""
AWS_S3_SECRET_ACCESS_KEY = ""
AWS_S3_ENDPOINT_URL = ""
AWS_STORAGE_BUCKET_NAME = ""

The storage.py with the custom Cached Storage should look something like this:

from django.core.files.storage import storages
from storages.backends.s3 import S3Storage

class CachedS3Storage(S3Storage):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.local_storage = storages.create_storage({
            "BACKEND": "compressor.storage.CompressorFileStorage"
        })

    def save(self, name, content, max_length=None):
        self.local_storage.save(name, content)
        super().save(name, self.local_storage._open(name))
        return name

    def path(self, name):
        return self.local_storage.path(name)

Relevant environment files:

PYTHONPATH=/var/pretix/your-settings-module # (/yourmodule/*.py -> where your files live)
DJANGO_SETTINGS_MODULE=yourmodule.settings
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment