一个好方法是从请求中继承Session 对象。一个基本的例子:
from requests import Session
class MyClient(Session):
"""Specialized client that inherits the requests api."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def get_google(self):
return self.get("http://google.com")
MyClient 包含免费的 Session (request) api,以及您想要添加的任何其他内容。
一个真实的例子:假设客户端需要在运行时指定的身份验证标头(在这种情况下,身份验证需要当前时间戳)。这是一个示例客户端,它继承了 Session 和子类 AuthBase,实现了这一点(此代码需要为 api_key、secret_key、密码设置值):
import json, hmac, hashlib, time, requests, base64
from requests.auth import AuthBase
from requests import Session
class MyClient(Session):
"""Client with specialized auth required by api."""
def __init__(self, api_key, secret_key, passphrase, *args, **kwargs):
# allow passing args to `Session.__init__`
super().__init__(*args, **kwargs)
# `self.auth` callable that creates timestamp when request is made
self.auth = MyAuth(api_key, secret_key, passphrase)
class MyAuth(AuthBase):
"""Auth includes current timestamp when called.
https://docs.python-requests.org/en/master/user/advanced/#custom-authentication
"""
def __init__(self, api_key, secret_key, passphrase):
self.api_key = api_key
self.secret_key = secret_key
self.passphrase = passphrase
def __call__(self, request):
timestamp = str(time.time())
message = timestamp + request.method + request.path_url + (request.body or "")
message = message.encode("utf-8")
hmac_key = base64.b64decode(self.secret_key)
signature = hmac.new(hmac_key, message, hashlib.sha256)
signature_b64 = base64.b64encode(signature.digest())
request.headers.update(
{
"ACCESS-SIGN": signature_b64,
"ACCESS-TIMESTAMP": timestamp,
"ACCESS-KEY": self.api_key,
"ACCESS-PASSPHRASE": self.passphrase,
"Content-Type": "application/json",
}
)
return request