ai_project_v1/minio_oss.py

101 lines
3.6 KiB
Python

from minio import Minio
from minio.error import S3Error
import os
client = Minio(
endpoint="112.44.103.230:9000", # MinIO 服务器地址
access_key="adminjdskfj", # 替换为你的 Access Key
secret_key="123456ksldjfal@Y", # 替换为你的 Secret Key
secure=False # 如果未启用 HTTPS 则设为 False
)
def create_bucket():
'''
访问 MinIO 服务器,打印存储桶
'''
try:
buckets = client.list_buckets()
for bucket in buckets:
print(f"Bucket: {bucket.name}, Created: {bucket.creation_date}")
except S3Error as e:
print(f"Error: {e}")
def downFile(object_name):
'''
下载文件
'''
# 要下载的桶名和对象名
bucket_name = "300bdf2b-a150-406e-be63-d28bd29b409f" # 你的桶名称
# 获取当前脚本所在目录
current_directory = os.path.dirname(os.path.abspath(__file__))
# 将文件下载到当前目录
download_path = os.path.join(current_directory, object_name)
try:
# 下载对象
client.fget_object(bucket_name, object_name, download_path)
print(f"文件已成功下载到 {download_path}")
return download_path
except S3Error as e:
print(f"下载文件时出错: {e}")
return None
def upload_folder(folder_path,bucket_directory):
"""
上传文件夹中的所有文件到 MinIO 指定目录
:param folder_path: 本地文件夹路径
:param bucket_name: MinIO 存储桶名称
:param bucket_directory: MinIO 存储桶内的目标目录(可选)
"""
# 要下载的桶名和对象名
bucket_name = "300bdf2b-a150-406e-be63-d28bd29b409f" # 你的桶名称
try:
# 确保存储桶存在
if not client.bucket_exists(bucket_name):
print(f"存储桶 {bucket_name} 不存在")
# 遍历文件夹中的所有文件
for root, _, files in os.walk(folder_path):
for file in files:
file_path = os.path.join(root, file)
object_name = os.path.relpath(file_path, folder_path).replace("\\", "/") # 适配 Windows/Linux
# 如果指定了桶目录,则添加前缀
if bucket_directory:
object_name = f"{bucket_directory.rstrip('/')}/{object_name}"
# 上传文件
client.fput_object(bucket_name, object_name, file_path)
print(f"文件 {file_path} 已上传至 {bucket_name}/{object_name}")
except S3Error as e:
print(f"上传文件夹时出错: {e}")
def upload_file(file_path,bucket_directory):
"""
上传文件到 MinIO 指定目录
:param file_path: 本地文件路径
:param bucket_name: MinIO 存储桶名称
:param bucket_directory: MinIO 存储桶内的目标目录(可选)
"""
# 要下载的桶名和对象名
bucket_name = "300bdf2b-a150-406e-be63-d28bd29b409f" # 你的桶名称
try:
# 确保存储桶存在
if not client.bucket_exists(bucket_name):
print(f"存储桶 {bucket_name} 不存在")
# 获取文件名
file_name = os.path.basename(file_path)
# 如果指定了桶目录,则添加前缀
if bucket_directory:
object_name = f"{bucket_directory.rstrip('/')}/{file_name}"
else:
object_name = file_name
# 上传文件
client.fput_object(bucket_name, object_name, file_path)
print(f"文件 {file_path} 已上传至 {bucket_name}/{object_name}")
return object_name,"pic"
except S3Error as e:
print(f"上传文件时出错: {e}")