如何通过Python API指定Dropbox根目录?调用时遇验证错误
Dropbox API根目录指定错误解决方法
尝试用空字符串表示Dropbox根目录读取文件时,触发验证错误,错误信息如下:
ValidationError("'%s' did not match pattern '%s'"
stone.backends.python_rsrc.stone_validators.ValidationError: 'test.txt' did not match pattern '(/(.|[
])|id:.)|(rev:[0-9a-f]{9,})|(ns:[0-9]+(/.*)?)'
用户调用代码:
# Path to the Dropbox folder you want to read files from FOLDER_PATH = "" def read_files_from_folder(): # Create a Dropbox client dbx = dropbox.Dropbox(TOKEN) try: # Get the list of files in the specified folder files = dbx.files_list_folder(FOLDER_PATH).entries for file in files: # Get the file metadata metadata = dbx.files_get_metadata(file.path_display) # Check if the file is a file (not a folder) if isinstance(metadata, dropbox.files.FileMetadata): # Get the file contents file_path = os.path.join(FOLDER_PATH, metadata.name) _, res = dbx.files_download(file_path) file_contents = res.content # Process the file contents as needed print(f"File Name: {metadata.name}") print(f"File Contents: {file_contents} {'=' * 50}") except dropbox.exceptions.ApiError as e: print(f"An error occurred: {e}") # Call the function to read files from the Dropbox folder read_files_from_folder()
解决方案
Dropbox API要求根目录必须用**"/"(单斜杠)**表示,而非空字符串。同时代码还有两处需要修正:
- 将根目录参数从空字符串改为
"/" - 不要用
os.path.join拼接Dropbox路径(本地路径拼接逻辑不适用于Unix风格的Dropbox路径),直接使用文件元数据中的path_display属性作为完整路径 - 无需重复调用
files_get_metadata,files_list_folder返回的条目已包含完整元数据
修正后的完整代码:
# Path to the Dropbox folder you want to read files from FOLDER_PATH = "/" def read_files_from_folder(): # Create a Dropbox client dbx = dropbox.Dropbox(TOKEN) try: # Get the list of files in the specified folder files = dbx.files_list_folder(FOLDER_PATH).entries for file in files: # 直接通过条目判断文件类型,无需重复请求元数据 if isinstance(file, dropbox.files.FileMetadata): # 使用Dropbox原生完整路径下载文件 _, res = dbx.files_download(file.path_display) file_contents = res.content # Process the file contents as needed print(f"File Name: {file.name}") print(f"File Contents:\n{file_contents}\n{'=' * 50}") except dropbox.exceptions.ApiError as e: print(f"An error occurred: {e}") # Call the function to read files from the Dropbox folder read_files_from_folder()
内容的提问来源于stack exchange,提问作者Devon
相关产品推荐
相关产品推荐

