简体   繁体   English

使用 python 请求进行抽象

[英]abstraction with python-requests

With urllib2 it is possible to do an abstraction of an URL request.使用 urllib2 可以对 URL 请求进行抽象。 So that you could do things with the requests body before the request is actually made.这样您就可以在实际发出请求之前对请求正文进行处理。

something like this for example:例如这样的事情:

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

I would like to use python-requests instead of urllib2.我想使用python-requests而不是 urllib2。 How could I achieve something like in the example above using it?我如何使用它实现上面示例中的功能?

You can create a 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)

or you can use a custom authentication object to encapsulate this process;或者您可以使用自定义身份验证对象来封装此过程; such an object is passed in the prepared request as the last step in preparation:这样的对象在准备好的请求中作为准备的最后一步传递:

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

then use this in your requests calls as the auth argument:然后在您的requests调用中使用它作为auth参数:

resp = requests.post(url, data=data, auth=BodySignature())

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

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