Python3与FastDFS分布式文件系统交互操作

59 阅读1分钟

fdfs-client-py3 是 FastDFS Python3 客户端,用于连接 FastDFS 分布式文件系统,通过fdfs-client-py3库可以很方便的与FastDFS分布式文件系统进行交互。具体使用方法见下文。

安装fdfs-client-py3

pip3 install fdfs-client-py3

创建配置文件

创建fdfs_tracker.conf配置文件,tracker_server改为实际IP

connect_timeout=30
network_timeout=60
tracker_server = xxx.xxx.xxx.xxx:22122
http.tracker_server_port = 80

创建Fdfs客户端实例

tracker_conf_path = "./fdfs_tracker.conf"   # tracker配置文件的地址
client = Fdfs_client(client=tracker_conf_path)

上传文件

调用upload_by_filename方法

# 上传文件
ret = client.upload_by_filename(r"C:\Test.txt") # 本地文件路径
print(ret)
​
# 返回信息:包括文件id,状态等。
{'Group name': 'group1', 'Remote file_id': 'group1/M00/00/B4/CiBwEmUonduAcRwJAAAAAAAAAAA997.txt', 'Status': 'Upload successed.', 'Local file name': 'C:\\Test.txt', 'Uploaded size': '0B', 'Storage IP': 'xxx.xxx.xxx.xxx'}

删除文件

调用delete_file方法,该方法接收remote_file_id参数。即上传文件后,返回的【Remote file_id】的值,同时需要将字符串encode编码才行。

# 删除文件
ret = client.delete_file(remote_file_id='group1/M00/00/B4/CiBwEmUonduAcRwJAAAAAAAAAAA997.txt'.encode("utf-8"))
print(ret)
# 返回信息
('Delete file successed.', b'group1/M00/00/B4/CiBwEmUopKaALfIKAAAAAAAAAAA447.txt', b'xxx.xxx.xxx.xx')

下载文件

调用download_to_file,并指定本地保存的路径,以及remote_file_id。

# 下载文件
ret = client.download_to_file(r'C:\Test1.txt', r'group1/M00/00/B4/CiBwEmUopKaALfIKAAAAAAAAAAA447.txt'.encode('utf-8'))
print(ret)
# 返回信息
{'Remote file_id': b'group1/M00/00/B4/CiBwEmUopKaALfIKAAAAAAAAAAA447.txt', 'Content': 'C:\\Test1.txt', 'Download size': '0B', 'Storage IP': b'xxx.xxx.xxx.xxx'}