Python教程

python 阿里oss上传文件封装

本文主要是介绍python 阿里oss上传文件封装,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
import traceback
from datetime import datetime
from logging import getLogger

import oss2
from django.conf import settings
from rest_framework import status

logger = getLogger('sms')


class OSS:
    def __init__(self, connect_timeout: int = 30):
        """
        :param connect_timeout: 连接超时时间
        """
        self.base_url: str = settings.OSS_BASE_URL
        self.connect_timeout: int = connect_timeout
        self.space_prefix: str = settings.OSS_SPACE_PREFIX
        self.auth_kwargs: dict = dict(
            access_key_id=settings.OSS_ACCESS_KEY_ID,
            access_key_secret=settings.OSS_ACCESS_KEY_SECRET
        )
        self.auth = oss2.Auth(**self.auth_kwargs)
        self.bucket_kwargs: dict = dict(
            auth=self.auth,
            endpoint=settings.OSS_ENDPOINT,
            bucket_name=settings.OSS_BUCKET_NAME,
            connect_timeout=connect_timeout
        )
        self.bucket = oss2.Bucket(**self.bucket_kwargs)

    def upload(
            self,
            file: bytes,
            file_name: str,
            category: str,
            user_code: str
    ) -> str:
        """
        上传单个文件

        :param file: 文件
        :param file_name: 文件名称(用户输入的名称)
        :param category: 文件类型
        :param user_code: 用户唯一编码
        :return: 文件上传后的URL
        """
        upload_date: str = str(datetime.now())
        upload_path = f"{self.space_prefix}/{user_code}/{category}/{upload_date}/{file_name}"
        fixed_path: str = self.base_url + upload_path
        upload_kwargs: dict = dict(
            key=upload_path,
            data=file,
        )
        try:
            response = self.bucket.put_object(**upload_kwargs)
            if response.status == status.HTTP_200_OK:
                return fixed_path
            logger.error(traceback.format_exc())
            logger.info(f'OSS文件上传错误 状态:{response.status}')
            print(f'OSS文件上传错误 状态:{response.status}')
            return ''
        except Exception as e:
            logger.error(traceback.format_exc())
            logger.info(f'OSS文件上传错误:{e}')
            print(f'OSS文件上传错误:{e}')
            return ''


oss_client = OSS()

这篇关于python 阿里oss上传文件封装的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!