如何将列表值作为API请求路径传递并修正URL格式错误
问题描述
我有一个名为enrollids的列表,内容如下:
['/path/one', '/path/two', '/path/three']
需要遍历该列表,将其中的值传入API调用,但当前代码返回URL格式错误(HTTP 406 Not Acceptable)。期望的正确URL格式应为:
"https://akab-2eznyq6aooxuiqkj-mrdlu75t6fnb6625.acps.net/path/one/deployments" "https://akab-2eznyq6aooxuiqkj-mrdlu75t6fnb6625.acps.net/path/two/deployments"
当前使用的代码如下:
akacer = result.json() enrollids = [enroll['location'] for enroll in akacer['enrollments']] for ssl in akacer['enrollments']: data = { 'enrollmentid': ssl['location'], } for i in enrollids: path= '{}/deployments'.format(i) headers = { "Accept": "application/vnd.acps.deployment.v7+json", } result = session.get(urljoin(baseurl, path), headers=headers, verify=False) deployments = result.json() print (deployments)
修正后的代码
akacer = result.json() enrollids = [enroll['location'] for enroll in akacer['enrollments']] # 直接遍历目标路径列表,无需嵌套外层循环 for path_segment in enrollids: # 拼接路径段与deployments后缀 path = f"{path_segment}/deployments" headers = { "Accept": "application/vnd.acps.deployment.v7+json", } full_url = urljoin(baseurl, path) result = session.get(full_url, headers=headers, verify=False) deployments = result.json() print(deployments)
修正说明
- 移除冗余嵌套循环:原代码中嵌套两层循环会导致重复请求,直接遍历
enrollids列表即可实现每个路径的单次请求。 - 确保路径拼接正确:通过
f-string拼接路径段和/deployments,结合urljoin与baseurl组合成完整的目标URL,符合API要求的格式。 - 406错误补充排查:若修正后仍出现406错误,需确认
Accept请求头的媒体类型是否与API文档要求完全一致,比如版本号、格式后缀是否正确。
内容的提问来源于stack exchange,提问作者francorocks
相关产品推荐
相关产品推荐

