Python 快速入門指南
適用於 Amazon S3 相容雲端儲存的 MinIO Python 用戶端 SDK

MinIO Python 用戶端 SDK 提供高階 API,以存取任何 MinIO 物件儲存或其他 Amazon S3 相容服務。
本快速入門指南涵蓋如何安裝 MinIO 用戶端 SDK、連線至物件儲存服務,以及建立範例檔案上傳器。
以下範例使用
MinIO
play
測試伺服器
play
伺服器是位於 https://play.min.io 的公用 MinIO 叢集。此叢集執行最新穩定版本的 MinIO,可用於測試和開發。範例中的存取憑證對公眾開放,所有上傳到 play
的數據都應被視為公開且世界可讀。
如需完整的 API 和範例清單,請參閱Python 用戶端 API 參考
安裝 MinIO Python SDK
Python SDK 需要 Python 版本 3.7+。您可以使用 pip
安裝 SDK,也可以從 minio/minio-py
GitHub 儲存庫安裝。
使用 pip
pip3 install minio
使用來自 GitHub 的原始碼
git clone https://github.com/minio/minio-py
cd minio-py
python setup.py install
建立 MinIO 用戶端
若要連線至目標服務,請使用 Minio()
方法建立 MinIO 用戶端,並使用以下必要參數:
參數 |
描述 |
---|---|
|
目標服務的 URL。 |
|
服務中用戶帳戶的存取金鑰 (使用者 ID)。 |
|
用戶帳戶的秘密金鑰 (密碼)。 |
例如
from minio import Minio
client = Minio("play.min.io",
access_key="Q3AM3UQ867SPQQA43P2F",
secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG",
)
範例 - 檔案上傳器
此範例執行下列操作:
使用提供的憑證連線至 MinIO
play
伺服器。建立名為
python-test-bucket
的儲存區 (如果該儲存區尚不存在)。從
/tmp
上傳名為test-file.txt
的檔案,並重新命名為my-test-file.txt
。使用
mc ls
驗證檔案是否已建立。
file_uploader.py
# file_uploader.py MinIO Python SDK example
from minio import Minio
from minio.error import S3Error
def main():
# Create a client with the MinIO server playground, its access key
# and secret key.
client = Minio("play.min.io",
access_key="Q3AM3UQ867SPQQA43P2F",
secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG",
)
# The file to upload, change this path if needed
source_file = "/tmp/test-file.txt"
# The destination bucket and filename on the MinIO server
bucket_name = "python-test-bucket"
destination_file = "my-test-file.txt"
# Make the bucket if it doesn't exist.
found = client.bucket_exists(bucket_name)
if not found:
client.make_bucket(bucket_name)
print("Created bucket", bucket_name)
else:
print("Bucket", bucket_name, "already exists")
# Upload the file, renaming it in the process
client.fput_object(
bucket_name, destination_file, source_file,
)
print(
source_file, "successfully uploaded as object",
destination_file, "to bucket", bucket_name,
)
if __name__ == "__main__":
try:
main()
except S3Error as exc:
print("error occurred.", exc)
執行此範例
在
/tmp
中建立名為test-file.txt
的檔案。若要使用不同的路徑或檔名,請修改source_file
的值。使用以下命令執行
file_uploader.py
python file_uploader.py
如果伺服器上不存在儲存桶(bucket),輸出將類似如下
Created bucket python-test-bucket
/tmp/test-file.txt successfully uploaded as object my-test-file.txt to bucket python-test-bucket
使用
mc ls
驗證上傳的檔案
mc ls play/python-test-bucket
[2023-11-03 22:18:54 UTC] 20KiB STANDARD my-test-file.txt
更多參考資料
深入探索
貢獻
許可證
本 SDK 是在 Apache License, Version 2.0 許可下發布的,詳情請參閱 LICENSE 和 NOTICE。