python 2.7 minio 文件上传
时间: 2024-09-15 20:05:26 浏览: 50
在Python 2.7中,使用MinIO库进行文件上传相对简单。首先,你需要安装`minio`客户端库,可以使用pip命令:
```bash
pip install minio
```
然后,你需要准备以下几个步骤:
1. **初始化连接**:需要获取MinIO服务器的 endpoint、access key和secret key,这通常是存储在配置文件或者环境变量中的。
```python
from minio import Minio
mc = Minio(
'your-minio-endpoint',
access_key='your-access-key',
secret_key='your-secret-key',
secure=False # 如果是HTTPS,则设为True,默认是False
)
```
2. **创建bucket(如果不存在)**:如果要在MinIO上创建一个新的存储桶,可以在上传文件之前调用`make_bucket()`方法。
```python
if not mc.bucket_exists('your-bucket-name'):
mc.make_bucket('your-bucket-name')
```
3. **上传文件**:使用`put_object()`函数将本地文件上传到指定路径。
```python
file_path = '/path/to/local/file.txt'
object_name = 'file.txt'
try:
mc.put_object(
bucket_name='your-bucket-name',
object_name=object_name,
file_path=file_path
)
except Exception as e:
print(f"Error uploading file: {e}")
```
完整示例代码如下:
```python
import os
from minio import Minio
# ... (初始化连接)
def upload_file_to_minio(file_path, object_name):
try:
with open(file_path, 'rb') as f:
mc.put_object(bucket_name='your-bucket-name', object_name=object_name, data=f)
print(f"File uploaded successfully: {file_path} to {object_name}")
except Exception as e:
print(f"Failed to upload file: {e}")
# 使用方法
upload_file_to_minio('/path/to/local/file.txt', 'file.txt')
```
阅读全文