使用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.我怎样才能实现上面使用它的例子呢?
您可以创建准备好的请求:
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)
或者您可以使用自定义身份验证对象来封装此过程; 这样的对象在准备好的请求中作为准备的最后一步传递:
import hashlib class BodySignature(object): def __init__(self, header='Authorization', algorithm=hashlib.md5): self.header = header self.algorithm = algorithm def __call__(self, request): body = request.body if not isinstance(body, bytes): # Python 3 body = body.encode('latin1') # standard encoding for HTTP signature = self.algorithm(body) request.headers[self.header] = signature.hexdigest() return request
然后在你的requests
调用中使用它作为auth
参数:
resp = requests.post(url, data=data, auth=BodySignature())