我有许多函数正在使用 requests 调用 api .因此,许多调用类似于下面的调用(针对此示例进行了简化):
requests.get(url, data=data, auth=('user','password'))
所有请求都将被验证,我想找到一种更简洁的方法来验证所有请求,而不是仅包括 auth=('user','password') 部分每次通话。
我的第一个想法是创建一个继承自 requests 类的子类,然后覆盖 get 函数。如下所示:
class authRequests(requests):
def get(url, data):
return requests.get(url, data=data, auth=('user', 'password'))
然后使用 authRequests.get 而不是 requests.get。我没有丰富的 Python 经验,所以这可能不是一个有效的示例,但我想知道这是否是正确的方法,或者我是否应该使用不同的方法来执行此操作?
请您参考如下方法:
你应该使用 requests.Session()在不同的请求中保持事物:
Sessions can also be used to provide default data to the request methods. This is done by providing data to the properties on a
Sessionobject
with requests.Session() as session:
session.auth = ('user', 'password')
session.get(url, data=data1)
response = session.post(another_url, data=data2)
