【问题标题】:Customize django-storage s3 url?自定义 django-storage s3 url?
【发布时间】:2013-09-27 03:21:24
【问题描述】:
我正在使用 django-storages 让用户将图像文件上传到我的 S3,并且我有一个与 s3 中的存储桶一起使用的云端分发。
我可以将文件上传到 s3,但我无法将图像文件的 url 更改为使用 cloudfront 分发 url。
url 始终设置为 s3 存储桶 url。
有没有办法自定义url?
谢谢
【问题讨论】:
标签:
django
amazon-s3
cdn
amazon-cloudfront
django-storage
【解决方案2】:
我采取的解决这个问题的方法是创建一个名为“static_cdn”的新模板标签;它会做一些检查,说“我是本地的、开发的、生产的等等”,并会根据域的位置适当地调整域。如果我只是在本地搞事情(或者,至少我还没有),那么生成 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)