验证所有请求的最佳方法?

2024-10-04 01:32:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有许多函数正在使用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经验,所以这可能不是一个有效的例子,但我想知道这是否是正确的方法,或者我是否应该使用不同的方法来实现这一点?你知道吗


Tags: 方法函数authapiurldatagetdef
1条回答
网友
1楼 · 发布于 2024-10-04 01:32:24

您应该使用^{}跨不同的请求持久化内容:

Sessions can also be used to provide default data to the request methods. This is done by providing data to the properties on a Session object

with requests.Session() as session:
    session.auth = ('user', 'password')

    session.get(url, data=data1)
    response = session.post(another_url, data=data2)

相关问题 更多 >