如果不缓存 access_token 应用很容易超出每天 2000 次的请求上限。
set 方法中的 ttl 可按实际需求就行调整,下面的代码中默认设置为 3600 秒。

from django.core.cache import cache
from wechatpy.session import SessionStorage


class DjangoDefaultStorage(SessionStorage):
    """
    使用django默认的缓存方法缓存请求微信接口的access_token
    wechatpy: https://docs.wechatpy.org/zh_CN/stable/quickstart.html#accesstoken
    微信官方:https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html
    """
    def __init__(self, *args, **kwargs):
        pass

    def get(self, key, default=None):
        return cache.get(key, default)

    def set(self, key, value, ttl=3600):
        cache.set(key, value, ttl)

    def delete(self, key):
        cache.delete(key)

编写以上方法后,在调用的代码部分使用以下方式调用:

session_interface = DjangoDefaultStorage()
client = WeChatClient(WECHAT_APP_ID, WECHAT_APP_SECRET, session=session_interface)

标签: Django, wechatpy

添加新评论