简体   繁体   中英

abstraction with python-requests

With urllib2 it is possible to do an abstraction of an URL request. 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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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