将params传递给requests.Session.get引发TypeError

时间:2017-11-23 18:34:48

标签: python python-3.x python-requests

我试图理解为什么将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

1 个答案:

答案 0 :(得分:2)

问题在于get需要only one un-named (positional) argument

def get(self, url, **kwargs):
    # ...

您提供了两个:urlparams

要解决此问题,您需要提供params作为命名(关键字)参数:

return self.session.get(url, params=params)