色彩时光 | 记录程序员世界的点点滴滴

基于七牛存储的django文件处理


在当下云概念大行其道的时候,云处理,云存储这些为广大中小应用和网站带了更多实惠,也为有心人提供了开始的机会。尝试使用新浪sae 服务搭建django网站,同时将文件存储在七牛 ,以求达到最大的利用。


1、在settings.py进行七牛基本配置,七牛python sdk代码模板放入libs目录进行解析,七牛云存储:www.qiniu.com


'''
        七牛配置
'''
import sys
sys.path.append("libs")#七牛python sdk代码模板放入libs目录进行解析
QINIU_ACCESS_KEY = 'K5SEj5mB_qB64j3wNN1CjppnpiFzXpKId0qGc4x9'
QINIU_SECRET_KEY = '6O_Ai3a45pvFD2OPv4zVs9PgHOoDiErFIb8vqSpQ'
QINIU_BUCKET_DEFAULT = 'rgbtimeweb'
QINIU_URL='7sbq50.com1.z0.glb.clouddn.com'
QINIU_UPLOAD_TO="http://7sbq50.com1.z0.glb.clouddn.com/"

2、基于七牛python sdk的文件处理工具类,文档地址:http://developer.qiniu.com/docs/v6/sdk/python-sdk.html


# encoding=utf-8
__author__ = 'lh'

from mysite import settings
from datetime import date
from time import time
from qiniu import Auth
from qiniu import BucketManager
from qiniu.services.storage.uploader import put_data

def uploadFile(name,data):
    #上传文件
    """
        :param name 文件名 data 文件流
        :return 文件存储地址
    """
    try:
        print "=========uploadFile==========="
        qiniu_url=settings.QINIU_URL
        bucket_name=settings.QINIU_BUCKET_DEFAULT
        access_key=settings.QINIU_ACCESS_KEY
        secret_key=settings.QINIU_SECRET_KEY
        q = Auth(access_key, secret_key)
        token = q.upload_token(bucket_name)

        filetype=name.split('.')[-1].lower()
        new_filename="%s.%s"%(getTimeName(),filetype)
        print new_filename
        ret, info = put_data(token, new_filename, data)

        '''print "ret:%s"%ret
        print "info:%s"%info
        print info.status_code'''

        return_url=''
        if info is not None:
            if info.status_code==200:
                return_url="http://%s/%s"%(qiniu_url,ret["key"])
            else:
                print('error: %s ' % info['exception'])
        return return_url
    except:
        raise

def deleteFile(url):
    #删除文件
    """
        :param url: 文件地址
        :return: 成功与否
    """
    try:
        print "========deleteFile========="
        access_key = settings.QINIU_ACCESS_KEY
        secret_key = settings.QINIU_SECRET_KEY
        bucket_name = settings.QINIU_BUCKET_DEFAULT
        qiniu_url=settings.QINIU_URL
        url_str=str(url)
        name=url_str.replace("http://%s/"%qiniu_url,'')

        q = Auth(access_key, secret_key)
        bucket = BucketManager(q)
        ret, info = bucket.delete(bucket_name, name)
        if info.status_code==200:
            return True
        else:
            return False
    except:
        raise

def getInfo(url):
    #获取文件信息
    """
    :param url:文件地址
    :return:文件信息
    """
    access_key = settings.QINIU_ACCESS_KEY
    secret_key = settings.QINIU_SECRET_KEY
    bucket_name = settings.QINIU_BUCKET_DEFAULT

    q = Auth(access_key, secret_key)
    bucket = BucketManager(q)
    ret, info = bucket.stat(bucket_name, url)
    print(ret,info)
    assert 'hash' in ret
    return info

def getTimeName():
    #日期_时间戳 生成文件名
    return "%s_%s"% (str(date.today()),str(time()))

3、models.FieldFile自定义文件存储storage,_save中进行文件存储


class QiniuStorage(FileSystemStorage):
    def __init__(self, location=settings.MEDIA_ROOT, base_url=settings.MEDIA_URL):
        #初始化
        location="/"
        base_url="http://7sbq50.com1.z0.glb.clouddn.com/"
        super(QiniuStorage, self).__init__(location, base_url)

    def _open(self,name,mode='rb'):
        file=File(open(name,mode))
        #print "qiniuStorage open %s|%s"%(name,file)
        return file

    def _save(self,name,content):
        #print "qiniuStorage save"
        name=tool.uploadFile(content.name,content)
        return name

    def get_available_name(self,name):
        #print "qiniuStorage get_available_name %s"%name
        return name

    def get_valid_name(self, name):
        #print "qiniuStorage get_valid_name %s"%name
        return name

    def exists(self, name):
        #print "qiniuStorage exists %s"%name
        try:
            tool.getInfo(name)
        except:
            raise
        return True

    def listdir(self, path):
        #print "qiniuStorage listdir"
        pass

    def size(self, name):
        #print "qiniuStorage size"
        return 0

    def url(self, name):
        #print "qiniuStorage url"
        return name

    def path(self, name):
        #print "qiniuStorage path"
        return name

    def delete(self, name):
        #print "qiniuStorage delete"
        return name

4、自定义models.Model模型 修改文件字段前删除以前存储在云存储上的对应文件,删除该条记录时删除对应云存储的文件。django1.3起支持signals,详细:http://stackoverflow.com/questions/16041232/django-delete-filefield


upload_to=settings.QINIU_UPLOAD_TO   
class MyModel(models.Model):
        img=models.FileField(upload_to=upload_to,verbose_name=u'配图',storage=QiniuStorage())
@receiver(models.signals.pre_save,sender=MyModel)
def myModelPreSave(sender, instance, **kwargs):
    #保存前文件处理
    if instance.pk is not None:
        signature=Signature.objects.get(pk=instance.pk)
        tool.deleteFile(signature.img)
    #print "signaturePreSave"

@receiver(models.signals.pre_delete,sender=MyModel)
def myModelPreDelete(sender, instance, **kwargs):
    #删除前文件处理
    if instance.pk is not None:
        signature=Signature.objects.get(pk=instance.pk)
        tool.deleteFile(signature.img)


您可能也对下面文章感兴趣:

Write a Comment


* Content (required) 10~500s

分类

热门标签

友情链接