繁体   English   中英

使用 python 请求进行抽象

[英]abstraction with 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。 我如何使用它实现上面示例中的功能?

您可以创建一个准备好的请求

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM