使用aws s3+cloudfront为django提供安全存储
djamazing的Python项目详细描述
djazing[d__me_z_]提供了一种使用s3+cloudfront作为django存储的方法。它有 与传统存储相比,它可以生成签名的url,因此只有 能够显示url的用户也能够访问它。DJ惊人 可以在两种模式下工作:
- unprotected mode
- In this mode the storage simply generates URL-s to cloudfront. The cloudfront distribution should be publicly accessible. This can be used for files that don’t require special security.
- protected mode
- The URLs are signed in this model using the ^{tt1}$. These signatures are only valid for the current user. Please remember that it is up to the developer to ensure that the signed URLs are created only when the user that can access them is logged in (some kind of per-row authorization should probably be in place). After clicking these a special view redirects the user to a signed cloudfront URL. This URL is only valid for a very small amount of time.
AWS配置
- 创建一个s3 bucket。
- 为可以访问bucket的用户生成密钥对。
- 创建一个源于bucket的cloudfront分发 仅限于已签名的URL。
- (对于保护模式)生成可在中使用的CloudFront密钥对
- 分布。
安装
安装djazing by pip:
$ pip install djamazing
注意:如果你使用django 1.10的djazing 未发布的django threadlocals版本
$ pip install git+https://github.com/nebstrebor/django-threadlocals.git
将"djamazing.storage.DjamazingStorage"设置为默认的文件存储。
配置DJamazing:
DJAMAZING = { 'CLOUDFRONT_KEY': b"""-----BEGIN RSA PRIVATE KEY----- (...) -----END RSA PRIVATE KEY-----""", 'CLOUDFRONT_KEY_ID': '...', 'CLOUDFRONT_URL': 'http://....cloudfront.net/', 'S3_KEY_ID': '...', 'S3_SECRET_KEY': '...', 'S3_BUCKET': '...', 'SIGNATURE_TIMEOUT': datetime.timedelta(seconds=2), }
对于无保护模式,省略CLOUDFRONT_KEY和CLOUDFRONT_KEY_ID 钥匙。 如果要在文件^{tt5}中存储cloudfornt密钥$ 参数也可以用于文件路径。 请注意,签名超时是不需要任何人工操作的时间 交互时,只需浏览器来处理重定向。如果未指定-它 默认为1.5秒。
添加threadlocals中间件 'threadlocals.middleware.ThreadLocalMiddleware'到您的MIDDLEWARE
在urls.py:
url(r'^djamazing/', include(djamazing.urls)),
在一个项目中使用各种配置
如果要在一个项目中使用各种配置(例如 静态文件和保护上传),您可以使用继承。创建一个 DjamazingStoragelike的简单子类:
class StaticStorage(DjamazingStorage): """Storage for static files""" def __init__(self): super(StaticStorage, self).__init__(settings.STATIC_DJAMAZING)
现在您可以将其用作存储空间,如:
STATICFILES_STORAGE = 'some.path.StaticStorage' STATIC_DJAMAZING = { ... }
而STATIC_DJAMAZING配置将重写DJAMAZING 此存储的配置。