python本地连接minio
在你浏览器能成功访问到你的minio网页,并且成功登录之后。接下来如果你想用python连接数据库,并且想用python连接minio,就可以用这个blog。
连接代码
client = Minio("localhost:9000", #9000是默认端口号
access_key="admin", #你的账户
secret_key="password", #你的密码
secure= False, #这点我会详细说明
)
为什么要用到这行代码
secure= False, #这点我会详细说明
如果不用的话,你可能会报这样的错误
Traceback (most recent call last): File "D:\environment\python\Lib\site-packages\urllib3\connection.py", line 198, in _new_conn sock = connection.create_connection( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\environment\python\Lib\site-packages\urllib3\util\connection.py", line 85, in create_connection raise err File "D:\environment\python\Lib\site-packages\urllib3\util\connection.py", line 73, in create_connection sock.connect(sa) ConnectionRefusedError: [WinError 10061] 由于目标计算机积极拒绝,无法连接。
这里涉及到了ulib库里面底层的东西,这里直接给大家看minio库里面的逆天代码
self._base_url = BaseURL(
("https://" if secure else "http://") + endpoint,
region,
)
这是minio官方包里面的代码,就是如果你secure(默认为true)true,他就会把你的"localhost:9000"这行代码前面+上https//,但是由于我们本地是http而不是https然后就会出现这样的bug,而不是什么端口开放的问题。
查看桶是否存在 创建桶
bucket_name = "python-test-bucket"
#查看桶是否存在
found = client.bucket_exists(bucket_name)
if not found:
#创建桶
client.make_bucket(bucket_name)
print("Created bucket", bucket_name)
这段代码的意思是查看桶是否存在,如果不存在就创建桶。
上传文件
#桶名字
bucket_name = "python-test-bucket"
#上传后文件的名字
destination_file = "my-test-file.txt"
#要上传的文件
source_file = "./tmp/test-file.txt"
client.fput_object(
bucket_name, destination_file, source_file,
)
这段代码的意思是,在上传 你本机./tmp/test-file.txt文件,并命名成my-test-file.txt(destination_file),到python-test-bucket桶里面。
合起来代码就是
from minio import Minio
client = Minio("localhost:9000", #9000是默认端口号
access_key="admin", #你的账户
secret_key="password", #你的密码
secure= False, #这点我会详细说明
)
bucket_name = "python-test-bucket"
#查看桶是否存在
found = client.bucket_exists(bucket_name)
if not found:
#创建桶
client.make_bucket(bucket_name)
print("Created bucket", bucket_name)
#上传后文件的名字
destination_file = "my-test-file.txt"
#要上传的文件
source_file = "./tmp/test-file.txt"
client.fput_object(
bucket_name, destination_file, source_file,
)