Python Requests:使用Session.get()时为何出现参数数量错误?
问题
在为Requests请求实现504错误重试机制时,运行代码报错:get() takes 2 positional arguments but 3 were given,但明明只传了两个参数。未使用Session和mount的旧代码可以正常运行,具体信息如下:
错误栈
Exception has occurred: TypeError get() takes 2 positional arguments but 3 were given File "...", line 113, in my_function s.get("https://epqs.nationalmap.gov/v1/json", payload) File "...", line 158, in <module> d = my_function(l) TypeError: get() takes 2 positional arguments but 3 were given
出错代码
payload = { "x": coordinate[0], "y": coordinate[1], "wkid": 4326, "units": "Meter", "includeDate": "false", } s = requests.Session() retries = Retry( total=10, backoff_factor=1, status_forcelist=[502, 503, 504], ) s.mount("https://", HTTPAdapter(max_retries=retries)) s.get("https://epqs.nationalmap.gov/v1/json", payload)
可正常运行的旧代码
payload = { "x": coordinate[0], "y": coordinate[1], "wkid": 4326, "units": "Meter", "includeDate": "false", } r = requests.get("https://epqs.nationalmap.gov/v1/json", payload)
问题原因与解决方法
问题出在参数传递的方式差异:
- 全局的
requests.get()函数允许将请求参数作为第二个位置参数传入(对应params参数) - 但
requests.Session.get()方法的第二个位置参数是timeout,而非params。直接传payload时,Session方法会自动绑定自身为第一个参数self,导致payload被当成第三个位置参数,触发参数数量错误。
修正只需将payload显式指定为params关键字参数:
修正后的代码
payload = { "x": coordinate[0], "y": coordinate[1], "wkid": 4326, "units": "Meter", "includeDate": "false", } s = requests.Session() retries = Retry( total=10, backoff_factor=1, status_forcelist=[502, 503, 504], ) s.mount("https://", HTTPAdapter(max_retries=retries)) # 显式指定params参数 s.get("https://epqs.nationalmap.gov/v1/json", params=payload)
建议日常编写代码时都显式指定params关键字参数,避免因API方法差异引发类似问题。
内容的提问来源于stack exchange,提问作者the_meter413
相关产品推荐
相关产品推荐

