python使用s3协议调用minio教程
时间: 2024-12-16 07:14:53 浏览: 16
在Python中,通过Boto3库可以方便地使用S3协议调用MinIO存储服务。MinIO是一个开源的对象存储服务器,通常用于备份、存储和处理大量数据。以下是使用Boto3连接MinIO并上传、下载文件的基本步骤:
**安装Boto3库**:
首先确保已经安装了`boto3`,如果没有,你可以通过pip安装:
```bash
pip install boto3
```
**配置AWS SDK for Python (Boto3) with MinIO credentials**:
由于MinIO通常运行在自定义端口443(HTTP)或9000(HTTPS),你需要创建一个IAM角色或者临时凭证,并设置环境变量或配置文件。这里假设你有预设的MinIO用户名(`ACCESS_KEY`)和密码(`SECRET_KEY`),以及访问URL(如`http://your-minio-server.com:9000`)。
```python
import os
MINIO_ACCESS_KEY = 'YOUR_ACCESS_KEY'
MINIO_SECRET_KEY = 'YOUR_SECRET_KEY'
MINIO_ENDPOINT = 'http://your-minio-server.com:9000'
# 设置AWS S3兼容的配置
os.environ['AWS_ACCESS_KEY_ID'] = MINIO_ACCESS_KEY
os.environ['AWS_SECRET_ACCESS_KEY'] = MINIO_SECRET_KEY
os.environ['AWS_DEFAULT_REGION'] = 'us-east-1' # 如果你的MinIO服务器不是在美国东部,更改此值
os.environ['USE_MINIO_INTEGRATION'] = 'true'
```
**连接到MinIO和基本操作**:
1. 初始化S3资源:
```python
from botocore.exceptions import NoCredentialsError
import boto3
try:
s3 = boto3.resource('s3', endpoint_url=MINIO_ENDPOINT)
except NoCredentialsError as e:
print(f"Could not load credentials: {e}")
```
2. 上传文件:
```python
def upload_file_to_minio(bucket_name, object_name, file_path):
try:
s3.Bucket(bucket_name).upload_file(file_path, object_name)
print(f"{file_path} uploaded to {bucket_name}/{object_name}")
except Exception as e:
print(f"Failed to upload file: {e}")
# 示例
bucket_name = "my-bucket"
file_path = "/path/to/local/file.txt"
upload_file_to_minio(bucket_name, file_name, file_path)
```
3. 下载文件:
```python
def download_file_from_minio(bucket_name, object_name, save_path):
try:
s3.Bucket(bucket_name).download_file(object_name, save_path)
print(f"{object_name} downloaded from {bucket_name} to {save_path}")
except Exception as e:
print(f"Failed to download file: {e}")
# 示例
download_file_from_minio(bucket_name, "file.txt", "/path/to/save/downloaded/file.txt")
```
阅读全文