Django亚马逊s3 SuspiciousOperation

时间:2014-08-22 22:28:06

标签: django amazon-web-services amazon-s3 boto django-storage

因此,当我尝试从浏览器访问S3上的某个图像时,一切正常。但是当python这样做时我得到SuspiciousOperation错误。 我的静态文件夹在S3上是公共的,所以我真的不知道它来自哪里。

Publication.objects.get(id=4039).cover.url
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/vagrant/.pyenv/versions/blook/lib/python2.7/site-packages/django/db/models/fields/files.py", line 64, in _get_url
    return self.storage.url(self.name)
  File "/home/vagrant/.pyenv/versions/blook/lib/python2.7/site-packages/queued_storage/backends.py", line 291, in url
    return self.get_storage(name).url(name)
  File "/home/vagrant/.pyenv/versions/blook/lib/python2.7/site-packages/queued_storage/backends.py", line 115, in get_storage
    elif cache_result is None and self.remote.exists(name):
  File "/home/vagrant/.pyenv/versions/blook/lib/python2.7/site-packages/storages/backends/s3boto.py", line 410, in exists
    name = self._normalize_name(self._clean_name(name))
  File "/home/vagrant/.pyenv/versions/blook/lib/python2.7/site-packages/storages/backends/s3boto.py", line 341, in _normalize_name
    name)
SuspiciousOperation: Attempted access to 'http:/s3-eu-west-1.amazonaws.com/xpto/static/images/default-image.png' denied.

我的设置:

AWS_S3_SECURE_URLS = True  # use http instead of https
S3_URL = 'http://s3-eu-west-1.amazonaws.com/%s' % AWS_STORAGE_BUCKET_NAME
MEDIA_ROOT = 'media/'
STATIC_ROOT = '/static/'
STATIC_URL = S3_URL + STATIC_ROOT
MEDIA_URL = S3_URL + '/' + MEDIA_ROOT

现在我可以解决它,但这不是一个长期的解决方案。任何想法?

1 个答案:

答案 0 :(得分:2)

Danigosa在这个帖子中的答案就是答案: django-storages and amazon s3 - suspiciousoperation

创建一个特殊的存储类,如本文所述: Using Amazon S3 to store your Django sites static and media files

然后覆盖_normalize_name,如下所示:

from django.conf import settings
from storages.backends.s3boto3 import S3Boto3Storage


class StaticStorage(S3Boto3Storage):

    location = settings.STATICFILES_LOCATION

    def _clean_name(self, name):
        return name

    def _normalize_name(self, name):
        if not name.endswith('/'):
            name += "/"

        name += self.location
        return name


class MediaStorage(S3Boto3Storage):

    location = settings.MEDIAFILES_LOCATION

    def _clean_name(self, name):
        return name

    def _normalize_name(self, name):
        if not name.endswith('/'):
            name += "/"

        name += self.location
        return name

最后 - (至少在Python 3上)不要使用

{% load static from staticfiles %}

在你的模板中。

坚持:

{% load static %}