oss 常用语句
# -*- coding: UTF-8 -*-
'''
@Project :03-crawler
@File :oss.py
@Author :yucaifu
@Date :2024/3/26 16:18
@Description :
'''
# https://help.aliyun.com/zh/oss/developer-reference/simple-upload-1?spm=a2c4g.11186623.0.0.17275a05FGcsYG
import oss2
import requests
from yscredit_tools.config import OSS_KEY_ID, OSS_KEY_SECRET, endpoint
class DomeOSS(object):
def __init__(self):
self.oss = {"oss_bucket_name": 'ys-customer-output', "oss_file_path": 'getui'}
self.bucket = oss2.Bucket(oss2.Auth(OSS_KEY_ID, OSS_KEY_SECRET), endpoint, self.oss["oss_bucket_name"])
def bucket_state(self): # 判断bucket是否存在
try:
self.bucket.get_bucket_info()
return True
except oss2.exceptions.NoSuchBucket:
return False
def object_state(self, oss_name): # 判断文件是否存在
exist = self.bucket.object_exists('{}/{}'.format(self.oss["oss_file_path"], oss_name))
if exist:
print("文件存在", exist)
else:
print("文件不存在", exist)
return exist
def uplode_local_file(self, oss_name, file_name): # 上传本地文件
if not self.object_state(oss_name):
result = self.bucket.put_object_from_file('{}/{}'.format(self.oss["oss_file_path"], oss_name), file_name)
print('上传状态码: {}'.format(result.status))
def upload_requests_file(self, url, oss_name):
if not self.object_state(oss_name):
input = requests.get(url)
result = self.bucket.put_object('{}/{}'.format(self.oss["oss_file_path"], oss_name), input)
print('上传状态码: {}'.format(result.status))
def upload_append_file(self, oss_name, file_name): # 追加上传
# result = self.bucket.append_object('{}/{}'.format(self.oss["oss_file_path"], oss_name), 0, file_name) # 首次上传
result = self.bucket.head_object('{}/{}'.format(self.oss["oss_file_path"], oss_name))
result = self.bucket.append_object('{}/{}'.format(self.oss["oss_file_path"], oss_name), result.content_length, file_name) # 非首次上传
print('上传状态码: {}'.format(result.status))
def download_file_locat(self, oss_name, file_name):
result = self.bucket.get_object_to_file('{}/{}'.format(self.oss["oss_file_path"], oss_name), file_name)
print('下载状态码: {}'.format(result.status))
if __name__ == '__main__':
oss = DomeOSS()
# oss.bucket_state()
# oss.object_state()
# oss.uplode_local_file("政策-浙江政务服务网_test.xlsx", "C:\\Users\\Ad\\Desktop\\政策-浙江政务服务网_test.xlsx")
# oss.download_file_locat("政策-浙江政务服务网_test.xlsx", "C:\\Users\\Ad\\Desktop\\政策-浙江政务服务网1_test.xlsx")
oss.upload_append_file("政策-浙江政务服务网_test.xlsx", "C:\\Users\\Ad\\Desktop\\政策-浙江政务服务网_test.xlsx")