用python请求抽象

时间:2013-11-29 16:36:50

标签: python python-requests

使用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。我怎么能用上面的例子来实现呢?

1 个答案:

答案 0 :(得分:5)

您可以创建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来封装此过程;这样的对象在准备好的请求中作为准备的最后一步传递:

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())