You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

同步API替换异步API后Python脚本报KeyError: 'jobId'求助

问题排查与解决

核心原因

API从异步v3升级为同步v4后,响应结构完全改变:同步接口不会返回jobId字段——因为同步模式下请求会直接返回结果,不需要创建异步任务再轮询获取。你仍沿用异步逻辑去提取jobId,自然触发KeyError。

排查步骤

  1. 先打印完整的API响应,确认同步接口的返回格式:
    在报错代码前添加一行:
    print("POST Response Content:", job_id_req.text)
    
    运行后就能看到v4接口实际返回的JSON结构,比如可能直接包含downloadUrl,或者直接返回数据内容。

解决方案

根据同步API的特性,重构请求逻辑,去掉异步任务的轮询流程:

修改后的核心代码示例

def main():
    Headers = {
        'Content-Type':'application/json',
        'Username':'**',
        'Password':'**',
        'DeveloperToken':'***'
    }
    post_url='https://searchapi.pubcenter.com/api/v4/report'
    
    for index in range(2):
        file_date = str(date.today()- timedelta(index+1))
        print('API请求日期: {}'.format(file_date))
        payload = {
            'reportName':'Distribution PTQS Report',
            'reportType':'DISTRIBUTIONPTQS',
            'startDate':file_date,
            'endDate':file_date,
            'granularity':'Day',
            'columns':[
                'Date','PartnerCode','Adcountry','DeviceType','PTQS','ImpactScore'
            ]
        }
        
        job_id_req = requests.post(url=post_url, data=json.dumps(payload), headers=Headers)
        print('请求状态码: {}'.format(str(job_id_req.status_code)))
        
        # 先解析响应JSON
        try:
            response_json = json.loads(job_id_req.text)
        except json.JSONDecodeError:
            print('响应不是合法JSON:', job_id_req.text)
            continue
        
        # 同步接口逻辑:直接获取下载链接(根据实际响应字段调整)
        if job_id_req.status_code == 200:
            # 假设同步接口直接返回downloadUrl,若实际返回数据则直接处理
            download_url = response_json.get('downloadUrl')
            if not download_url:
                print('未找到下载链接,响应内容:', response_json)
                continue
            
            ns_api_file = requests.get(url=download_url)
            # 这里可以用一个临时标识代替jobId,比如file_date
            upload_s3_file(ns_api_file, file_date, file_date)
        else:
            print('API调用失败,响应:', response_json)

额外优化点

  • 用response_json.get("key")代替直接索引,避免KeyError,同时可以设置默认值
  • 添加JSON解析异常捕获,处理接口返回非JSON的情况
  • 同步接口不需要轮询,去掉原有的while循环逻辑

注意事项

如果打印后发现v4接口直接返回CSV数据而非下载链接,可直接将job_id_req.content传入upload_s3_file处理,不需要再请求下载链接。

内容的提问来源于stack exchange,提问作者learnto code

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 19:07:15