2013-09-21 39 views
1

我正在使用django-storages让用户将图像文件上传到我的S3,并且我有一个cloudfront发行版与s3中的存储区一起工作。自定义django-storage s3 url?

我能够将文件上传到s3,但我无法更改图像文件的URL以使用cloudfront分发网址。

url始终设置为s3存储桶网址。

有没有办法自定义网址?

感谢

+0

也许你会想重载[URL方法(https://docs.djangoproject.com/en/dev/ref/files/存储/#django.core.files.storage.Storage.url) –

回答

0

解决这个问题,我采取了一个办法,就是创建一个名为“static_cdn”新templatetag;它会做一些检查来说“我是本地人,开发人员,制作人员等等”,并且会根据它在哪里适当地涉入域。如果我只是在本地搞乱(或者至少我还没有),那么生成CDN流量是没有意义的。

我考虑的另一种方法是完全覆盖默认的静态标签,并将逻辑放在那里,但现在我想保持粒度,因此,如果出于某种原因,我想直接从S3中获取和不是生产服务器上的CloudFront,我有这种能力。

编辑:示例代码可能是这个样子:

# Import: Django 
from django.template import Library 
from django.templatetags.static import static 

# Static CDN 
# - We could probably go in and overwrite the default static template tag 
# and decide to use the CDN or not; for now, though, I want the option 
# (even remotely) to explicitly use the CDN or not. 
def static_cdn(url): 
    if not LOCAL_ENVIRONMENT: 
     # StackOverflow: Do not do this! Import/Write/etc an urljoin (see Django code 
     # for examples - you can probably import the version Django uses internally. 
     return 'https://{0}{1}{2}'.format(AWS_CLOUDFRONT_DOMAIN, STATIC_URL, url) 
    else: 
     return static(url) 

# Register 
register = Library() 
register.simple_tag(static_cdn)