python post请求上传文件至minio
时间: 2025-01-04 22:14:25 浏览: 14
### 使用Python通过POST请求上传文件至MinIO
为了实现向MinIO服务器发送文件,可以利用`requests`库来构建并执行HTTP POST请求。下面展示了一个具体的例子,在这个实例中,假设已经配置好了MinIO服务,并知晓访问所需的URL、密钥等必要参数。
首先安装必要的依赖项:
```bash
pip install requests
```
接着按照如下方式编写代码片段用于上传操作[^1]:
```python
import os
import requests
from requests.auth import HTTPBasicAuth
def upload_file_to_minio(file_path, bucket_name, object_name=None):
"""
Uploads a file to the specified MinIO server.
:param file_path: Path of local file.
:param bucket_name: Name of destination bucket on MinIO.
:param object_name: (Optional) Object name within MinIO. If not provided,
filename will be used as object name.
"""
minio_url = "http://your-minio-server-url"
access_key = 'YOUR-ACCESS-KEY'
secret_key = 'YOUR-SECRET-KEY'
if object_name is None:
object_name = os.path.basename(file_path)
url = f"{minio_url}/{bucket_name}/{object_name}"
with open(file_path, 'rb') as data:
response = requests.put(
url=url,
auth=HTTPBasicAuth(access_key, secret_key),
data=data
)
if response.status_code == 200 or response.status_code == 204:
print(f'Successfully uploaded {file_path} to {url}')
else:
raise Exception('Failed to upload', response.text)
if __name__ == '__main__':
test_file = '/path/to/your/file.txt' # Replace with your actual file path
target_bucket = 'my-bucket-name' # Your desired bucket name here
try:
upload_file_to_minio(test_file, target_bucket)
except Exception as e:
print(e)
```
需要注意的是上述代码中的`put()`方法被用来替代传统的`post()`方法来进行对象存储API调用;这是因为S3兼容的对象存储系统(如MinIO),通常遵循RESTful API设计模式,其中PUT动词更适合表示资源创建或更新动作。
阅读全文