簡體   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