python django结合七牛云存储图片
2019-05-25 本文已影响0人
小梨的十三
settings里设置

QINIU_ACCESS_KEY ='Oo9PxPHACtVScG-YgAHiM9htuRd1LLOxZhdpZBk' # 个人中心的KEY
QINIU_SECRET_KEY ='744J6A85OsW0a9bu_gRN4vR5BNX1HyJbGVcZuby' # 个人中心的SECRET
QINIU_BUCKET_NAME ='zhengqi' #仓库名字

安装 pip install qiniu

import io
import uuid
import qiniu
from PILimport Image
from django.confimport settings
from django.httpimport HttpResponse
q = qiniu.Auth(settings.QINIU_ACCESS_KEY, settings.QINIU_SECRET_KEY)
def upload(img):
_img = img.read()
size =len(_img) / (1024 *1024)# 上传图片的大小 M单位
image = Image.open(io.BytesIO(_img))
key =str(uuid.uuid1()).replace('-','')
name ='upfile.{0}'.format(image.format)# 获取图片后缀(图片格式)
if size >1:
# 压缩
x, y = image.size
im = image.resize((int(x /1.73),int(y /1.73)), Image.ANTIALIAS)# 等比例压缩 1.73 倍
else:
# 不压缩
im = image
im.save('./media/' + name)# 在根目录有个media文件
path ='./media/' + name
token = q.upload_token(settings.QINIU_BUCKET_NAME, key,3600, )
qiniu.put_file(token, key, path)
url ='www.zhengqi1995.com.qiniudns.com/{}'.format(key)
return url
def uploadpic(request):
img = request.FILES['file']
url = upload(img)
return HttpResponse(url)