python代码上传文件到fastdfs

Install

直接pip安装,需要Python3.10+

pip install fastdfs-client

Initial client

可以用其他教程的client.conf配置文件的方式,也可以直接传入ip列表进行初始化

from fastdfs_client import FastdfsClient

client = FastdfsClient(trackers=('ip1', 'ip2', ...))

Upload by filename

这个返回的内容跟其他Python SDK相同,只是把返回值里的bytes解码成str

ret = client.upload_by_filename('test.txt')
print(ret)
# {"Group name":"group1","Status":"Upload successed.", "Remote file_id":"group1/M00/00/00/
#	wKjzh0_xaR63RExnAAAaDqbNk5E1398.py","Uploaded size":"6.0KB","Local file name":"test"
#	, "Storage IP":"192.168.243.133"}

Upload as url

其实我只需要这个函数,pypi和github上能搜到的包,基本都是在上一步就报错了,而且它们都需要xxx.conf文件作为传入参数
感觉很没必要,所以干脆自己封装一个更加简单易用的

url = client.upload_as_url(b'...', suffix='jpeg')
print(url)
# http://<ip1>/group1/M00/00/00/xxx.jpeg

Real Example

实例

import sys
from pathlib import Path
from fastdfs_client import FastdfsClient

client = FastdfsClient("dfs.waketzheng.top")
# Or:
# client = FastdfsClient(
#    trackers=("120.77.47.33",),
#    ip_mapping={"120.77.47.33": "https://dfs.waketzheng.top"},
# )

p = Path("a.jpg")
if sys.argv[1:] and (_p := Path(sys.argv[1])).exists():
    p = _p
ret = client.upload_as_url(p.read_bytes(), p.suffix)  # 本地文件路径
print(ret)
# https://dfs.wakethzheng.top/group1/M00/00/00/eE0vIWZExnaAUx0mAAXiLDPsKR4172.jpg
posted @ 2024-05-15 22:30  waketzheng  阅读(117)  评论(0编辑  收藏  举报