将会话添加到类代码

时间:2018-03-18 11:21:14

标签: python session

原始代码可以正常使用:

class Sms:
    def __init__(self, api_key):
        self.key = api_key
        self.url = 'http://sms.com'

    def request(self, action):
        params = {**{'api_key': self.key}, **action.data}
        response = requests.get(self.url, params)
        return response.text

我需要添加会话连接: 我这样做:

class Sms:
    def __init__(self, api_key):
        self.key = api_key
        self.url = 'http://sms.com'

    def get_tor_session():
        session = requests.session()
        # Tor uses the 9050 port as the default socks port
        session.proxies = {'http':  'socks5://127.0.0.1:9150',
                           'https': 'socks5://127.0.0.1:9150'}
        return session

    def request(self, action, session=get_tor_session()):
        params = {**{'api_key': self.key}, **action.data}
        response = session.get(self.url, params)
        return response.text

但后来我收到了错误:

TypeError: get() takes 2 positional arguments but 3 were given

如何编写正确的语法?

1 个答案:

答案 0 :(得分:1)

get只有一个位置参数

get(url, **kwargs)

如文档http://docs.python-requests.org/en/master/api/#sessionapi中所述。您必须通过关键字参数传递params