new_candy

导航

django中云存储静态文件

Django自带文件存储系统存储在本地文件夹,如果我们将文件存储在云端,需要自定义文件存储系统。

自定义文件存储系统需要继承django.core.files.storage.Storage

from django.core.files.storage import Storage

class QiNiuStorage(Storage):

添加deconstructible装饰器以允许在迁移数据库时进行迁移

from django.utils.deconstruct import deconstructible

@deconstructible
class QiNiuStorage(Storage):

在配置文件中增加

# 七牛云存储图片文件
QINIU_ACCESS_KEY = "你的云平台秘钥"
QINIU_SECRET_KEY = "你的云平台私钥"
QINIU_BUCKET_NAME = "云平台空间名"
QINIU_BUCKET_DOMAIN = "http://云存储空间域名/"  # 需要将域名拼接成完整的路径
DEFAULT_FILE_STORAGE = "云存储工具类路径"

重写django保存文件的默认方法,url方法返回文件完整路径,存储在数据库中

from django.conf import settings
from qiniu import Auth, put_data
@deconstructible
class QiNiuStorage(Storage): def _open(self, name, model='rb'): """不用打开,代码省略""" pass def _save(self, name, content):
    # content文件内容
if name is None: name = content.name try: q = Auth(settings.QINIU_ACCESS_KEY, settings.QINIU_SECRET_KEY) token = q.upload_token(settings.QINIU_BUCKET_NAME)
       # ret['key']存储文件名 ret, info
= put_data(token, None, content.read()) print(ret, info) except Exception as e: raise e if info.status_code != 200: raise Exception("上传图片失败") return settings.QINIU_BUCKET_DOMAIN + ret['key'] def url(self, name): return name def exists(self, name): """七牛云自动解决文件重名问题""" return False

 Django中设置字段类型

logo = models.FileField(max_length=64, verbose_name="企业logo")

posted on 2018-10-11 14:41  new_candy  阅读(428)  评论(0编辑  收藏  举报