You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

wechatmp_client.py 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import time
  2. import threading
  3. from channel.wechatmp.common import *
  4. from wechatpy.client import WeChatClient
  5. from common.log import logger
  6. from wechatpy.exceptions import APILimitedException
  7. class WechatMPClient(WeChatClient):
  8. def __init__(self, appid, secret, access_token=None,
  9. session=None, timeout=None, auto_retry=True):
  10. super(WechatMPClient, self).__init__(
  11. appid, secret, access_token, session, timeout, auto_retry
  12. )
  13. self.fetch_access_token_lock = threading.Lock()
  14. def clear_quota(self):
  15. return self.post("clear_quota", data={"appid": self.appid})
  16. def clear_quota_v2(self):
  17. return self.post("clear_quota/v2", params={"appid": self.appid, "appsecret": self.secret})
  18. def fetch_access_token(self): # 重载父类方法,加锁避免多线程重复获取access_token
  19. with self.fetch_access_token_lock:
  20. access_token = self.session.get(self.access_token_key)
  21. if access_token:
  22. if not self.expires_at:
  23. return access_token
  24. timestamp = time.time()
  25. if self.expires_at - timestamp > 60:
  26. return access_token
  27. return super().fetch_access_token()
  28. def _request(self, method, url_or_endpoint, **kwargs): # 重载父类方法,遇到API限流时,清除quota后重试
  29. try:
  30. return super()._request(method, url_or_endpoint, **kwargs)
  31. except APILimitedException as e:
  32. logger.error("[wechatmp] API quata has been used up. {}".format(e))
  33. response = self.clear_quota_v2()
  34. logger.debug("[wechatmp] API quata has been cleard, {}".format(response))
  35. return super()._request(method, url_or_endpoint, **kwargs)