首页 > 解决方案 > 如何从 yandexcloud 连接 django s3 文件存储?

问题描述

有来自yandex云的s3 https://cloud.yandex.com/docs/storage/tools/?utm_source=console&utm_medium=empty-page&utm_campaign=storage

我如何配置 django 来使用它?

标签: djangoamazon-s3django-storageyandexcloud

解决方案


一)安装boto3anfdjango-storages

II)yandex_s3_storage.py使用下一个代码添加文件

from storages.backends.s3boto3 import S3Boto3Storage

from sites.crm.settings import YOUR_YANDEX_BUCKET_NAME


class ClientDocsStorage(S3Boto3Storage):
    bucket_name = YANDEX_CLIENT_DOCS_BUCKET_NAME
    file_overwrite = False

III)在设置中添加下一个代码

INSTALLED_APPS = [
    ...
    'storages',
    ...
]

...

# ----Yandex s3----
DEFAULT_FILE_STORAGE = 'yandex_s3_storage.ClientDocsStorage'  # path to file we created before
YANDEX_CLIENT_DOCS_BUCKET_NAME = 'client-docs'
AWS_ACCESS_KEY_ID = env('AWS_ACCESS_KEY')
AWS_SECRET_ACCESS_KEY = env('AWS_SECRET_ACCESS_KEY')
AWS_S3_ENDPOINT_URL = 'https://storage.yandexcloud.net'
AWS_S3_REGION_NAME = 'storage'

IV)将文件字段添加到您的模型

from sites.yandex_s3_storage import ClientDocsStorage

class ClientDocs(models.Model):
    ... 
    upload = models.FileField(storage=ClientDocsStorage())
    ... 

推荐阅读