原理
封装api
import requests
class BaseApi:
def request_http(self,req):
# 直接用关键字传参方式,把请求提传给requests.request方法,**解码字典
r = requests.request(**req)
#print(r.json())
return r
调用
import requests
import yaml
from string import Template
from api.base_api import BaseApi
class GetToken(BaseApi):
_corpid = "xxxx"
_corp_secret = "yyyy"
def template(self):
with open("../api/gettoken.yaml") as f:
data = {
"corpid": self._corpid,
"corp_secret": self._corp_secret
}
re = Template(f.read()).substitute(data)
return yaml.safe_load(re)
def get_token(self):
req = self.template()
r = self.request_http(req)
#r = requests.request(**req)
#等同于下面这个
#r = requests.request(method="get",url="https://qqyapi.weixin.qq.com/cgi_bin/gettoken",params={"corpid":self._corpid,"corp_secret": self._corp_secret})
print(r.json)
return r
def add_token(self):
pass
if __name__ == '__main__':
ba = GetToken()
ba.get_token()