TOSFS是Proton Python Client的开源版实现。它构建在火山引擎TOS Python SDK之上,为访问TOS(对象存储)提供了便捷的Python文件系统接口。
TOSFS适用于需要使用Python进行对象存储操作的场景,如:
云存储应用:开发者可以基于TOSFS构建云存储应用,提供文件的在线存储、访问和管理功能。
数据处理与分析:在数据处理和分析过程中,需要将大量数据存储在云端,并通过Python程序进行访问和处理。TOSFS提供了便捷的文件操作接口,有助于简化这一过程。
备份与恢复:使用TOSFS可以便捷地将重要数据进行备份,并在需要时快速恢复。
您可以通过如下pip命令从PyPI库下载TOSFS,并自动安装到Python环境中。
pip install tosfs
from tosfs.core import TosFileSystem tosfs = TosFileSystem( key='<用户实际的AK>', secret='<用户实际的SK>', endpoint_url='http://tos-cn-beijing.volces.com', # 内网使用请换成内网endpoint region='cn-beijing', )
# 配置 (ak & sk) 或者 assume role的session token 两者二选一 export TOS_ACCESS_KEY=' <用户实际的AK> ' export TOS_SECRET_KEY=' <用户实际的SK> ' export TOS_SECURITY_TOKEN=' <用户实际的session token> ' export TOS_ENDPOINT='http://tos-cn-beijing.volces.com' export TOS_REGION='cn-beijing'
确认以上环境变量生效后,通过使用 EnvCredentialsProvider
来进行初始化。
import os from tosfs.core import TosFileSystem from tos import EnvCredentialsProvider tosfs = TosFileSystem( endpoint_url=os.environ.get("TOS_ENDPOINT"), region=os.environ.get("TOS_REGION"), credentials_provider=EnvCredentialsProvider, # must )
按照上述指导获取TosFileSystem的实例后,我们可以访问fs和文件操作API:
import os from tosfs.core import TosFileSystem # init TosFileSystem fs = TosFileSystem( endpoint_url="https://your-tos-endpoint", key="your-access-key", secret="your-secret-key", region="your-region" ) local_file_path = "localfile.txt" remote_file_path = "tos://your-bucket/remote_file.txt" # create a local file to upload with open(local_file_path, "w") as f: f.write("Hello TOSFS.") # upload to tos fs.put_file(local_file_path, remote_file_path) print(f"Uploaded {local_file_path} to {remote_file_path}") # download from tos downloaded_file_path = "downloaded_file.txt" fs.get_file(remote_file_path, downloaded_file_path) print(f"Downloaded {remote_file_path} to {downloaded_file_path}") # read content from downloaded local file with open(downloaded_file_path, "r") as f: content = f.read() print(f"Content of {downloaded_file_path}: {content}") # delete tos file fs.rm(remote_file_path) # write to tos with fs.open(remote_file_path, "w") as f: f.write("Hello TOSFS.") # read from tos with fs.open(remote_file_path, "r") as f: tos_content = f.read() print(f"Content of {remote_file_path}: {tos_content}") # clean local files os.remove(local_file_path) os.remove(downloaded_file_path)
TOSFS包与以下Python和fsspec版本兼容。
Version |
---|
3.9 |
3.10 |
3.11 |
3.12 |
Version |
---|
2023.5.0 |
2024.9.0 |
TOSFS 拥有详细的接口说明文档,详细信息请参考TOSFS Readthedocs API参考。