一个好的方法是从 requests 中的一个 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、passphrase设置值):
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):
super().__init__(*args, **kwargs)
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
__init__()
中做类似于self.session = requests.session()
的事情,然后执行像self.login()
这样的方法,调用例如self.session.get()
并执行更多操作...