发送HTTP请求时字典参数报500错误,如何正确使用字典参数?
解决requests字典传参返回500错误的问题
你遇到的500错误是因为目标API的查询参数格式并非标准的key=value键值对,而是采用函数调用式的参数项(比如eq(group,337)、ne(custom.field_28,R-404A))。当你用常规字典传参时,requests会自动将键值对转换为key=value格式(比如eq(group)=337),这与API预期的格式不匹配,导致服务器解析失败。
方法一:使用列表元组生成符合格式的参数
直接用列表包含元组的形式定义参数,每个元组的第一个元素是完整的函数式参数字符串,第二个元素设为None,这样requests会生成不带等号的参数项,与成功请求的格式完全一致:
import requests url = 'https://www.produktdatenbank-get.at/api/products' params = [ ('eq(group,337)', None), ('eq(instock,1)', None), ('ne(custom.field_28,R-404A)', None), ('ne(custom.field_28,R-407C)', None), ('ne(custom.field_28,R-417A)', None), ('ne(custom.field_28,R-410A)', None), ('eq(custom.field_133,1)', None), ('select(image,id,name,custom.field_22,custom.field_28,custom.field_133,subsidable,custom.field_78)', None), ('sort(+name)', None) ] headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:124.0) Gecko/20100101 Firefox/124.0', 'Accept': 'application/json', 'Accept-Encoding': 'identity', 'Accept-Language': 'en-US,en;q=0.9', 'Host': 'www.produktdatenbank-get.at', 'Referer': 'https://www.produktdatenbank-get.at/', 'X-Requested-With': 'XMLHttpRequest', } res = requests.get(url, params=params, headers=headers) print(res.status_code) print(res.json())
方法二:用字典维护参数逻辑,手动构建参数字符串
如果希望保持参数的可读性(比如按操作类型分组),可以先定义字典存储参数逻辑,再手动拼接成符合API要求的参数字符串:
import requests url = 'https://www.produktdatenbank-get.at/api/products' # 用字典维护参数逻辑,更易修改 params_config = { 'eq': [('group', '337'), ('instock', '1'), ('custom.field_133', '1')], 'ne': [('custom.field_28', 'R-404A'), ('custom.field_28', 'R-407C'), ('custom.field_28', 'R-417A'), ('custom.field_28', 'R-410A')], 'select': 'image,id,name,custom.field_22,custom.field_28,custom.field_133,subsidable,custom.field_78', 'sort': '+name' } # 手动构建符合API格式的参数字符串 params_parts = [] for op, content in params_config.items(): if op in ['eq', 'ne']: # 处理eq/ne类多参数 for field, value in content: params_parts.append(f"{op}({field},{value})") elif op in ['select', 'sort']: # 处理select/sort类单参数 params_parts.append(f"{op}({content})") params = '&'.join(params_parts) headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:124.0) Gecko/20100101 Firefox/124.0', 'Accept': 'application/json', 'Accept-Encoding': 'identity', 'Accept-Language': 'en-US,en;q=0.9', 'Host': 'www.produktdatenbank-get.at', 'Referer': 'https://www.produktdatenbank-get.at/', 'X-Requested-With': 'XMLHttpRequest', } res = requests.get(url, params=params, headers=headers) print(res.status_code) print(res.json())
内容的提问来源于stack exchange,提问作者MITHU
相关产品推荐
相关产品推荐

