promotion/handler/ad_image_upload.py

47 lines
1.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
# pip install -U cos-python-sdk-v5
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import logging
import os
from flask import Flask, jsonify, request
from flask_restful import reqparse, abort, Api, Resource
import pdb
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
class Cos_sdk(Resource):
def __init__(self):
secret_id = os.environ.get('cos_id')
secret_key = os.environ.get('cos_key')
region = 'ap-beijing' # 替换为用户的 Region
token = None # 使用临时密钥需要传入 Token默认为空可不填
scheme = 'https' # 指定使用 http/https 协议来访问 COS默认为 https可不填
config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme)
# 2. 获取客户端对象
self.client = CosS3Client(config)
self.bucket = "client-1256832210"
self.base_dirs = "ad"
self.url = "https://resource.kingsome.cn"
def post(self):
try:
import uuid
filename = "{}_{}".format(uuid.uuid1(), request.files.get('image-file').filename.split('.')[-1])
# filename = "{}_{}".format(uuid.uuid1(), request.files.get('image-file').filename)
body = request.files.get('image-file').read()
except Exception as e:
error = f"get filename={filename},body={body} , 'error' = {e}"
return jsonify({'code': 500, 'message': error})
cos_filename = f"{self.base_dirs}/{filename}"
url = f"{self.url}/{cos_filename}"
response = self.client.put_object(Bucket=self.bucket, Body=body, Key=cos_filename, StorageClass='STANDARD',
EnableMD5=False)
print(response)
return jsonify({'code': 200, 'message': {'url': url, 'response': response}})