python请求的抽象
使用urllib2,可以对URL请求进行抽象。因此,您可以在请求实际发出之前对请求主体进行处理 比如说: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
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())