Jef*_*opo 3 python oop inheritance specialization python-requests
我想专门化/子类化请求包,以添加一些具有自定义功能的方法。
我试图这样做:
# concrete_requests.py
import requests
class concreteRequests(requests):
def __init__(self):
super(concreteRequests, self).__init__()
self.session()
def login(self):
payload = {'user': 'foo', 'pass': 'bar'}
self.get('loginUrl', headers=header, data=payload)
# more login stuff...
# my_class.py
class MyClass:
def __init__():
self.requests = concreteRequests()
self.requests.login()
Run Code Online (Sandbox Code Playgroud)
这样,我仍然可以从self.requests成员和我的具体实现中受益。所以,我可以这样做:self.requests.get(...)或print(self.requests.post(...).status_code)等等。
我想这行super(concreteRequests, self).__init__()可能是愚蠢的无用,因为请求只是在导入中没有任何类声明。
因此,可以通过继承对请求包进行子类化/专门化吗?
requests是python模块而不是类。您只能继承类。
因此,基本上,您应该只在自己的自定义类中利用其方法/功能。
import requests
class MyRequests:
def __init__(self, username, passwd):
self.username = username
self.passwd = passwd
def get(self, *args, **kwargs):
# do your thing
resp = requests.get(...)
# do more processing
Run Code Online (Sandbox Code Playgroud)
我在上面写的只是一个让您前进的例子。
一个好方法是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")
Run Code Online (Sandbox Code Playgroud)
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):
# 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
Run Code Online (Sandbox Code Playgroud)