我试图理解为什么将params
传递给session.get
会在我的示例中引发TypeError。
response_get
会返回200
响应,而response_open
会引发TypeError。
import requests
class Foo:
def __init__(self):
self.session = requests.Session()
def get(self, url, params=None):
"""Return a Response object."""
return requests.get(url, params)
def open(self, url, params=None):
"""Return a Response object using the Session object."""
return self.session.get(url, params)
if __name__ == '__main__':
foo = Foo()
response_get = foo.get('https://estilen.github.io')
response_open = foo.open('https://estilen.github.io')
错误:
Traceback (most recent call last):
File "/home/estilen/Dropbox/Python/leapy/foo.py", line 21, in <module>
response_open = foo.open('https://estilen.github.io')
File "/home/estilen/Dropbox/Python/leapy/foo.py", line 15, in open
return self.session.get(url, params)
TypeError: get() takes 2 positional arguments but 3 were given
答案 0 :(得分:2)
问题在于get
需要only one un-named (positional) argument:
def get(self, url, **kwargs):
# ...
您提供了两个:url
和params
。
要解决此问题,您需要提供params
作为命名(关键字)参数:
return self.session.get(url, params=params)