Python自动化导出文件脚本报错:无文件可下载排查求助
问题描述
我用Python脚本从数据中心导出文件到文件夹,打算通过Windows计划任务实现自动化运行。调整示例脚本第8至20行的参数后,运行脚本时终端提示No files to download!,但系统中明确可见对应文件。已尝试设置Delivered和NotDeliverd状态参数,结果一致;脚本登录鉴权功能正常,VS Code中无语法错误。目前期望获取可下载文件列表,却始终得到无文件的提示。
脚本代码
import requests import json import os import re from urllib.parse import urlparse, unquote from pathlib import Path # SET THE API URL URL = "https://api.datalab.nrccua.org/v1" # SET YOUR API KEY API_KEY = "xxxx" # SET YOUR ORG UID ORGANIZATION_UID = "d1e01227-404d-439a-b7e8-12cfd11a6863" # override this if you want DOWNLOAD_DIR = os.path.dirname(__file__) DOWNLOAD_DIR = Path(DOWNLOAD_DIR) # SET USERNAME USERNAME = "xxxx@mailbox.sc.edu" # SET PASSWORD PASSWORD = "xxxx" def get_valid_filename(s): s = str(s).strip().replace(" ", "_") return re.sub(r"(?u)[^-\w.]", "", s) # SET YOUR USERNAME AND PASSWORD payload = {"userName": USERNAME, "password": PASSWORD, "acceptedTerms": True} session = requests.Session() # set the api key for the rest of the session session.headers.update({"x-api-key": API_KEY}) # login response_json = session.post(f"{URL}/login", data=json.dumps(payload)).json() if "sessionToken" not in response_json: print(f"Couldn't find sessionToken in response json:\n {response_json}") # set the authorization header for the rest of the session session.headers.update({"Authorization": f"JWT {response_json['sessionToken']}"}) # payload to return list of files get_exports_payload = {"status": "Delivered", "productKey": "score-reporter"} response_json = session.get( f"{URL}/datacenter/exports", params=get_exports_payload, headers={"Organization": ORGANIZATION_UID}, ).json() # loop through results files_to_download = [] for export in response_json: if "uid" in export: export_uid = export["uid"] # api route for download file_export_url = f"{URL}/datacenter/exports/{export_uid}/download" export_response_json = session.get(file_export_url, headers={"Organization": ORGANIZATION_UID}).json() if "downloadUrl" in export_response_json: files_to_download.append(export_response_json["downloadUrl"]) if len(files_to_download) == 0: print(f"No files to download!") else: for file in files_to_download: parsed_url = urlparse(file) # get the file name from the url, unescape it, and then replace whitespace with underscore escaped_filename = get_valid_filename(unquote(os.path.basename(parsed_url.path))) download_path = DOWNLOAD_DIR / escaped_filename print(f"Downloading file from url {file}") # don't use the session here download_file_response = requests.get(file, allow_redirects=True, stream=True) if download_file_response.ok: print(f"Writing file to {download_path}.") with open(download_path, "wb") as f: # we are going to chunk the download because we don't know how large the files are for chunk in download_file_response.iter_content(chunk_size=1024): if chunk: f.write(chunk) else: print(f"There was an error retrieving {file} with status code {download_file_response.status_code}.") print(f"{download_file_response.content}")
排查建议
- 修正状态参数拼写:你尝试的
NotDeliverd存在拼写错误,正确值应为NotDelivered,修正后重试。 - 核对productKey准确性:确认
productKey与系统中文件对应的产品标识完全匹配,包括大小写、特殊字符,可通过API文档核对合法取值。 - 打印API原始响应:在调用
/datacenter/exports接口后添加print(response_json),查看接口返回的原始数据,确认是否存在文件条目或隐藏的错误信息。 - 验证Organization头格式:部分API对请求头大小写敏感,尝试将
headers={"Organization": ORGANIZATION_UID}改为小写organization测试。 - 手动测试API接口:通过API调试工具手动调用
/datacenter/exports接口,传入相同参数、认证信息,对比返回结果,判断是脚本逻辑还是参数权限问题。 - 检查文件权限:确认当前登录账号拥有对应文件的下载权限,部分系统中文件可见但可能未分配下载权限。
内容的提问来源于stack exchange,提问作者sdgibbs
相关产品推荐
相关产品推荐

