Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python请求的抽象_Python_Python Requests - Fatal编程技术网

python请求的抽象

python请求的抽象,python,python-requests,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

使用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())
我想使用urllib2而不是urllib2。我如何使用它实现上面示例中的目标?

您可以创建一个:

或者,您可以使用封装该过程;这样的对象作为准备中的最后一步在准备好的请求中传递:

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
然后在
请求
调用中将其用作
auth
参数:

resp = requests.post(url, data=data, auth=BodySignature())
您可以创建一个:

或者,您可以使用封装该过程;这样的对象作为准备中的最后一步在准备好的请求中传递:

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
然后在
请求
调用中将其用作
auth
参数:

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