Python的抽象

2024-04-23 16:48:46 发布

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

使用urllib2,可以对URL请求进行抽象。这样您就可以在实际发出请求之前处理请求体。在

例如:

def authentication(self, req):
    signup = md5(str(req.get_data())).hexdigest()
    req.add_header('Authorization', signup)
    return urllib2.urlopen(req)

def some_request(self):
    url = 'http://something'
    req = urllib2.Request(url)
    response = authentication(req)
    return json.loads(response.read())

我想用python-requests代替urllib2。如何使用它来实现上面的示例中所示的功能?在


Tags: selfurldatagetauthenticationreturnresponsedef
1条回答
网友
1楼 · 发布于 2024-04-23 16:48:46

您可以创建prepared request

from requests import Request, Session

def authentication(self, req):
    signup = md5(str(req.body)).hexdigest()
    req.headers['Authorization'] = signup

s = Session()
req = Request('POST', url, data=data)
prepped = s.prepare_request(req)
authentication(prepped)

resp = s.send(prepped)

或者,您可以使用custom authentication object来封装此过程;在准备好的请求中传递这样一个对象作为准备的最后一步:

^{pr2}$

然后在您的requests调用中使用它作为auth参数:

resp = requests.post(url, data=data, auth=BodySignature())

相关问题 更多 >