使用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。如何使用它来实现上面的示例中所示的功能?在
您可以创建prepared request:
或者,您可以使用custom authentication object来封装此过程;在准备好的请求中传递这样一个对象作为准备的最后一步:
^{pr2}$然后在您的
requests
调用中使用它作为auth
参数:相关问题 更多 >
编程相关推荐