Django文件存储 自己定制存储系统解析

本文介绍了如何在Django中创建一个自定义的文件存储系统,包括遵循的步骤和关键方法的实现,如_open、_save和path。同时提到了Django Qiniu Storage的使用,详细阐述了配置环境变量、设置DEFAULT_FILE_STORAGE以及collectstatic命令的运行过程。通过QiniuStorage的代码示例,展示了如何利用requests库和七牛云API进行文件上传。
摘要由CSDN通过智能技术生成

要自己写一个存储系统,可以依照以下步骤:

1.写一个继承自django.core.files.storage.Storage的子类。


    from django.core.files.storage import Storage
    class MyStorage(Storage):
      ...

2.Django必须可以在无任何参数的情况下实例化MyStorage,所以任何环境设置必须来自django.conf.settings。


    from django.conf import settings
    from django.core.files.storage import Storage
     
    class MyStorage(Storage):
      def __init__(self, option=None):
        if not option:
          option = settings.CUSTOM_STORAGE_OPTIONS
        ...

3.根据Storage的open和save方法源码:


    def open(self, name, mode='rb'):
      """
      Retrieves the specified file from storage.
      """
      return self._open(name, mode)
     
     
    def save(self, name, content, max_length=None):
      """
      Saves new content to the file specified by name. The content should be
      a proper File object or any python file-like object, ready to be read
      from the beginning.
      """
      # Get the proper name for the file, as it will actually be saved.
      if name is None:
        name = content.name
     
      if not hasattr(content, 'chunks'):
        content = File(content, name)
     
      name = self.get_available_name(name, max_length=max_length)
      return self._save(name, content)

MyStorage需要实现_open和_save方法。

如果写的是个本地存储系统,还要重写path方法。

4.使用django.utils.deconstruct.deconstructible装饰器,以便在migration可以序列化。

还有,Storage.delete()、Storage.exists()、Storage.listdir()、Storage.size()、Storage.url()方法都会报NotImplementedError,也需要重写。

Django Qiniu Storage

七牛云有自己的django storage系统,可以看下是怎么运作的,地址 https://github.com/glasslion/django-
qiniu-storage

先在环境变量或者settings中配置QINIU_ACCESS_KEY、QINIU_SECRET_KEY、QINIU_BUCKET_NAME、QINIU_BUCKET_DOMAIN、QINIU_SECURE_URL。

使用七牛云托管用户上传的文件,在 settings.py 里设置DEFAULT_FILE_STORAGE:


    DEFAULT_FILE_STORAGE = 'qiniustorage.backends.QiniuStorage'

使用七牛托管动态生成的文件以及站点自身的静态文件,设置:


    STATICFILES_STORAGE = 'qiniustorage.backends.QiniuStaticStorage'

运行python manage.py collectstatic,静态文件就会被统一上传到七牛。

QiniuStorage代码如下:


    @deconstructible
    class QiniuStorage(Storage):
      """
      Qiniu Storage Service
      """
      location = ""
     
      def __init__(
          self,
          access_key=QINIU_ACCESS_KEY,
          secret_key=QINIU_SECRET_KEY,
          bucket_name=QINIU_BUCKET_NAME,
          bucket_domain=QINIU_BUCKET_DOMAIN,
          secure_url=QINIU_SECURE_URL):
     
        self.auth = Auth(access_key, secret_key)
        self.bucket_name = bucket_name
        self.bucket_domain = bucket_domain
        self.bucket_manager = BucketManager(self.auth)
        self.secure_url = secure_url
     
      def _clean_name(self, name):
        """
        Cleans the name so that Windows style paths work
        """
        # Normalize Windows style paths
        clean_name = posixpath.normpath(name).replace('\\', '/')
     
        # os.path.normpath() can strip trailing slashes so we implement
        # a workaround here.
        if name.endswith('/') and not clean_name.endswith('/'):
          # Add a trailing slash as it was stripped.
          return clean_name + '/'
        
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值