Python 将会话添加到类代码
原始代码可以正常工作:Python 将会话添加到类代码,python,session,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,
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
我需要添加会话以连接:
我有:
但后来我发现了一个错误:
TypeError: get() takes 2 positional arguments but 3 were given
如何编写正确的语法?
get
只有一个位置参数
get(url, **kwargs)
如文档中所述。您必须通过关键字参数传递
params
。name错误:名称'kwargs'未定义,但为什么response=requests.get(self.url,params)
有效,而不是response=session.get(self.url,params)
?因为response.get
具有以下签名:requests.get(url,params=None,**kwargs)
。它需要两个位置参数,可选参数必须作为关键字参数传递。请注意,params
也可以是关键字参数。您正在将params
类型的dict
作为位置参数传递。如果要将其作为键值对传递(您应该这样做,因为session.get
只获取一个位置参数)您需要使用**
(即**params
)将其解包。然后我得到了错误TypeError:request()得到了一个意外的关键字参数“api_key”
response=session.get(self.url,**params)
get(url, **kwargs)