Django Sorl-Thumbnail Signal Allows Automatic S3 CDN Synchronization
Pushing the load off on someone else is always nice. Amazon offers great services that allows you to do just that - while still maintaining control. Manually synchronizing your media with the Amazon S3 CDN Cloud would be time consuming. Try some simple signal code to update your media as needed automatically!
amazons3upload.models
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 | import subprocess
from django.db import models
from django.db.models.signals import post_save, pre_delete
from sorl.thumbnail.models import KVStore as sorlPicture
from sorl.thumbnail import images
DEST_BUCKET = 'acme'
S3_CONF = '/.s3cfg'
def s3_sorl_upload(sender, **kwargs):
if kwargs.has_key('instance') and not kwargs.get('instance') is None and not kwargs.get('instance').value is None:
instance = kwargs.get('instance')
try:
sorlImgThumb = images.deserialize_image_file(instance.value)
args = ['s3cmd', '--acl-public', 'put', '-c', S3_CONF,
os.path.join(settings.MEDIA_ROOT, sorlImgThumb.name),
's3://%s/%s' % (DEST_BUCKET, sorlImgThumb.name)]
p = subprocess.Popen(args)
post_save.connect(s3_sorl_upload,sorlPicture,dispatch_uid="s3_sorl_upload")
def s3_sorl_delete(sender, **kwargs):
if kwargs.has_key('instance') and not kwargs.get('instance') is None and not kwargs.get('instance').value is None:
instance = kwargs.get('instance')
try:
sorlImgThumb = images.deserialize_image_file(instance.value)
args = ['s3cmd', 'del', '-c', S3_CONF, 's3://%s/%s' % (DEST_BUCKET, sorlImgThumb.name)]
p = subprocess.Popen(args)
pre_delete.connect(s3_sorl_delete,sorlPicture,dispatch_uid="s3_sorl_delete")
|
templates/index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14 | {% load i18n thumbnail %}
<div class="img-box">
{% if object.image %}
{% if link %}
<a href="{{ link }}">
{% endif %}
{% thumbnail object.image "48x48" as img %}
<img src="{{ img.url }}" alt="{{ object.title }}" class="img" />
{% endthumbnail %}
{% if link %}
</a>
{% endif %}
{% endif %}
</div>
|
settings.py
| INSTALLED_APPS = (
'amazons3upload',
)
|

External Resources