| 
              # -*- coding: utf-8 -*-
import re
import pngquant
import qiniu
from django.conf import settings
from django_file_md5 import calculate_data_md5
from utils.thumbnail_utils import make_thumbnail2
QINIU = settings.QINIU
auth = qiniu.Auth(QINIU['access_key'], QINIU['secret_key'])
pngquant.config(settings.PNG_QUANT_FILE)
def generate_new_key(key, data):
    # key = re.sub(r"(.+/)(.+)\.(.+)", lambda m: '{}{}.{}'.format(m.group(1), calculate_data_md5(data), m.group(3)), key)
    sections = re.split(r'/|\.', key)
    base_path, ext = '/'.join(sections[:-2]), sections[-1]
    return '{}{}{}.{}'.format(base_path, base_path and '/', calculate_data_md5(data), ext)
def upload(data, key=None, mime_type='application/octet-stream', bucket=QINIU['bucket_default'], compress=True, thumbnail=True, thumbnailw=1080, thumbnailh=720):
    if not data:
        return ''
    if thumbnail:
        w, h = thumbnailw or 1080, thumbnailh or 720
        data = make_thumbnail2(data, w=w, h=h)
    if compress:
        try:
            data = pngquant.quant_data(data, ndeep=3)[1]
        except Exception as e:
            pass
    if (thumbnail or compress) and key:
        key = generate_new_key(key, data)
    token = auth.upload_token(bucket, key=key)
    ret, _ = qiniu.put_data(token, key, data, mime_type=mime_type)
    return ret.get('key')
def upload_file_admin(obj, key=None, mime_type='application/octet-stream', bucket=QINIU['bucket_default'], compress=True, thumbnail=True, thumbnailw=1080, thumbnailh=720):
    # Django Admin Upload
    if not obj.image:
        return ''
    obj.image.seek(0)
    return upload(obj.image.read(), key=key or obj.image.name, mime_type=mime_type, bucket=bucket, compress=compress, thumbnail=thumbnail, thumbnailw=thumbnailw, thumbnailh=thumbnailh)
def upload_file_req(file, key=None, mime_type='application/octet-stream', bucket=QINIU['bucket_default'], compress=True, thumbnail=True, thumbnailw=1080, thumbnailh=720):
    # photo = request.FILES.get('photo', '')
    # <InMemoryUploadedFile: photo.png (image/png)>
    if not file:
        return ''
    file.seek(0)
    return upload(file.read(), key=key or file.name, mime_type=mime_type, bucket=bucket, compress=compress, thumbnail=thumbnail, thumbnailw=thumbnailw, thumbnailh=thumbnailh)
def upload_file_path(path, key=None, mime_type='application/octet-stream', bucket=QINIU['bucket_default'], compress=True):
    if not path:
        return ''
    token = auth.upload_token(bucket, key=key)
    ret, _ = qiniu.put_file(token, key, path, mime_type=mime_type)
    return ret.get('key')
def qiniu_file_url(key, bucket=QINIU['bucket_default']):
    if not key:
        return ''
    return '{}/{}'.format(QINIU['buckets'][bucket] if settings.QINIU_FILE_URL_HTTPS else settings.QINIU_FILE_URL_AFTER, key)
 
  |