# -*- coding:utf-8 -*-
# @Time    : 2020/10/28 2:13 下午
# @Author  : Creat by Han
import requests
import os
import oss2
import json
from PIL.BufrStubImagePlugin import Image
from Crypto.Util.py3compat import BytesIO
from django.conf import settings
config_dict = settings.CONFIG



auth = oss2.Auth('LTAI4G7tFh5Nk4KXZoSPk1D8', 'RV4S2SfbLPoFNjlI4uIOoA0J1LQPQc')

def down_image(image_name,url):
    dir_name = os.path.dirname(image_name)
    if not os.path.isdir(dir_name):
        os.makedirs(dir_name)

    content = requests.get(url).content
    with open("%s"%image_name,"wb") as f:
        f.write(content)
    return image_name

def push_oss_image(data,http="https://oss-cn-beijing.aliyuncs.com",bt="bigdata-all"):
    try:
        http = config_dict["oss"]["http"]
        bt = config_dict["oss"]["bucket"]
        bucket = oss2.Bucket(auth,http,bt,connect_timeout=30)
        headers = {}
        headers["Content-Type"] = "image/jpg"
        headers["Content-Disposition"] = "inline"
        bucket.put_object_from_file(data[0].strip('/'), data[1],headers=headers)
        requests.adapters.DEFAULT_RETRIES = 5
        s = requests.session()
        s.keep_alive = False

        if os.path.exists(data[1]) == True:
            # 删除图片文件
            os.remove(data[1])
    except Exception as e:
        print("错误",e)
        pass
    return True


if __name__ == '__main__':
    # url = "http://image-yunfei.oss-cn-beijing.aliyuncs.com/202010/867435052201308/2020102840.jpg"
    base_path = "/data/image_result/"
    http = "http://bigdata-image.yfpyx.com/"
    addr = "202010/867435052201308/20201028211.jpg"
    # addr = "08-202/867435052201043/08-2020.jpg"
    image_path = base_path + addr.split('/')[-1]
    url = http+addr

    # data = ['/202010/867435052201308/up_2020102836.jpg', 'result_2020102836.jpg']
    # http = "http://oss-cn-beijing.aliyuncs.com"
    # bt = "image-yunfei"
    # push_oss_image(data=data,http=http,bt=bt)