Configure Amazon S3 for Mezzanine - a Django Blog engine

By: Varghese Chacko 1 year, 3 months ago

Amazon S3 is an efficient static file storage system for its services and relatively cheap. On the other hand Django is a nice web development framework that doesn't like to handle static files. Mezzanine is a popular blog engine  built in Django. Since Django doesn't like to handle static files on production systems, we always have to configure a web server like nginx or apache webserver to serve static files. On the other hand, its easy to host static files to Amazon S3. The S3 configuration for static files is easy, but saving user uploaded files for Django web app may raise some permission issues. Here is how we have configured the Django-S3-Mezzanine blog.

We use django-storages as the storage app. You can install it with pip as

pip install django-storages

The settingd for Django is

Add storages to installed apps

Configure Django to point to S3. The configuration we used is

"""
AMAZON S3 setup with Compress
"""
AWS_QUERYSTRING_AUTH = False
DEFAULT_S3_PATH = "media"
STATIC_S3_PATH = "static"

STATIC_URL = "https://{0}.s3.amazonaws.com/static/".format(AWS_STORAGE_BUCKET_NAME)

DEFAULT_FILE_STORAGE = 'atemon.storage_backends.MediaStorage'
STATICFILES_STORAGE = 's3_folder_storage.s3.StaticStorage'

MEDIA_ROOT = ""
MEDIA_URL = 'https://{0}.s3.amazonaws.com/' .format(AWS_STORAGE_BUCKET_NAME)
ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'

"""

AWS_STORAGE_BUCKET_NAME is your S3 bucket name . Note that MEDIA_ROOT need to be an empty string. Any value assigned to MEDIA_ROOT can pop up as permission issue

The S3BotoStorage engine may raise a directory listing issue while connecting to S3 and hence we have to define a custom class by sub-classing both S3BotoStorage and S3BotoStorageMixin. For this, you may create create a file storage_backends.py in your app and use this code.

from storages.backends.s3boto import S3BotoStorage
from filebrowser_safe.storage import S3BotoStorageMixin

class MediaStorage(S3BotoStorage, S3BotoStorageMixin):
    pass

Since we named our app as temon, we used configuration DEFAULT_FILE_STORAGE = 'atemon.storage_backends.MediaStorage'

The final configuration is to add CROS to your bucket

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>Authorization</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

 

Now you can test the application :)

Comments