django-storages + sorl_thumbnail + S3 不能很好地协同工作(URL 不匹配)

标签 django amazon-s3 boto sorl-thumbnail django-storage

我将 django-storages 和 sorl_thumbnail 一起使用,并将 Amazon S3 用于静态和媒体文件。我正在使用一个带有 2 个文件夹的存储桶,1 个用于静态文件夹,1 个用于媒体文件夹。

这是我的配置:

MEDIA_ROOT = '/media/'
MEDIA_URL = 'https://s3.amazonaws.com/my-bucket/media/'
STATIC_ROOT = '/static/'
STATIC_URL = 'https://s3.amazonaws.com/my-bucket/static/'
AWS_STORAGE_BUCKET_NAME = 'my-bucket'
DEFAULT_FILE_STORAGE = 'my_lib.s3utils.MediaRootS3BotoStorage'
STATICFILES_STORAGE = 'my_lib.s3utils.StaticRootS3BotoStorage'
MediaRootS3BotoStorageStaticRootS3BotoStorage定义如下:
StaticRootS3BotoStorage = lambda: S3BotoStorage(location='static')
MediaRootS3BotoStorage = lambda: S3BotoStorage(location='media')

当我使用 sorl_thumbnail 时,生成的缩略图位于正确的目录中:https://s3.amazonaws.com/my-bucket/media/cache但是当 sorl_thumbnail 试图检索一个已经存在的缩略图时,生成的 URL 是:https://s3.amazonaws.com/my-bucket/cache ,您会注意到 media文件夹被省略。

你知道我该如何解决这个问题吗?

我知道我可以只使用 django-storages 并将我的静态文件和媒体文件都混合在我的存储桶中,但这对我的口味来说有点太脏了:)

谢谢!

最佳答案

我能够通过定义 使其工作MediaRootS3BotoStorage StaticRootS3BotoStorage 如下:

from storages.backends.s3boto import S3BotoStorage
from django.conf import settings

class StaticRootS3BotoStorage(S3BotoStorage):
    """
    Storage for static files.
    """

    def __init__(self, *args, **kwargs):
        kwargs['location'] = 'static'
        super(StaticRootS3BotoStorage, self).__init__(*args, **kwargs)


class MediaRootS3BotoStorage(S3BotoStorage):
    """
    Storage for uploaded media files.
    """

    def __init__(self, *args, **kwargs):
        kwargs['location'] = 'media'
        super(MediaRootS3BotoStorage, self).__init__(*args, **kwargs)

此链接可能会有所帮助 https://github.com/jamstooks/django-s3-folder-storage

关于django-storages + sorl_thumbnail + S3 不能很好地协同工作(URL 不匹配),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12659655/

相关文章:

python - 如何从 python 字典中的列表中提取键的所有实例?

python - Django - 从每个组的最新日期检索对象 - PersonPhoto

python - 使用 Django 和 Gunicorn 在父级运行启动代码

amazon-web-services - AWS Redshift - 在卸载到 s3 时设置零件大小

amazon-web-services - 我可以使用 boto 将 "ok_action"添加到现有的 cloudwatch 警报而不创建新警报吗?

python - 从 S3 下载大量文件

python - 从views.py导入不适用于应用程序

django - 我的第一个 Django 项目

amazon-s3 - 亚马逊 s3 静态网络托管缓存

ruby - Amazon S3 在 Ruby SDK 中通过 URL 获取 S3 对象