使用python请求进行抽象



使用urlib2可以对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请求而不是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())

最新更新