Minio Python 客户端:直接上传字节

Minio Python Client: Upload Bytes directly

我阅读了 minio 文档,我看到了两种上传数据的方法:

我想测试 minio 并上传一些我刚用 numpy.random.bytes() 创建的数据。

如何在 python 解释器中上传存储在变量中的数据?

看看io.BytesIO。这些允许您将字节数组包装在一个流中,您可以将其提供给 minio。

例如:

import io
from minio import Minio

value = "Some text I want to upload"
value_as_bytes = value.encode('utf-8')
value_as_a_stream = io.BytesIO(value_as_bytes)

client = Minio("my-url-here", ...) # Edit this bit to connect to your Minio server
client.put_object("my_bucket", "my_key", value_as_a_stream , length=len(value_as_bytes))

我遇到了类似的情况:试图将 pandas DataFrame 作为羽毛文件存储到 minio 中。 我需要使用 Minio 客户端直接存储字节。最后代码看起来像这样:

from io import BytesIO
from pandas import df
from numpy import random
import minio

# Create the client
client = minio.Minio(
    endpoint="localhost:9000",
    access_key="access_key",
    secret_key="secret_key",
    secure=False
)

# Create sample dataset
df = pd.DataFrame({
    "a": numpy.random.random(size=1000),
})

# Create a BytesIO instance that will behave like a file opended in binary mode 
feather_output = BytesIO()
# Write feather file
df.to_feather(feather_output)
# Get numver of bytes
nb_bytes = feather_output.tell()
# Go back to the start of the opened file
feather_output.seek(0)

# Put the object into minio
client.put_object(
    bucket_name="datasets",
    object_name="demo.feather", 
    length=nb_bytes,
    data=feather_output
)

为了使 minio 能够插入正确数量的字节,我不得不使用 .seek(0)

@gcharbon:这个解决方案对我不起作用。 client.put_object() 只接受像对象这样的字节。

这是我的解决方案:

from minio import Minio 
import pandas as pd
import io  

#Can use a string with csv data here as well
csv_bytes = df.to_csv().encode('utf-8')

csv_buffer = io.BytesIO(csv_bytes)

# Create the client
client = Minio(
    endpoint="localhost:9000",
    access_key="access_key",
    secret_key="secret_key",
    secure=False
)

client.put_object("bucketname", 
                  "objectname",  
                  data=csv_buffer, 
                  length=len(csv_bytes), 
                  content_type='application/csv')