公众号5秒回复文件解决办法---附2种办法

本文介绍了在微信客户端5秒内未接收到请求时,通过使用缓存机制(如ExpiringDict)和Python的lru_cache装饰器来提高响应效率的两种方法,分别展示了如何应用在WeRoBot模块中。
摘要由CSDN通过智能技术生成

解决微信客户端5秒未拿到请求时的回复问题
都是两种方法

演示均已 werobot 模块为例,其余模块一样

第一种方法

使用缓存机制

import time

import werobot
from werobot.replies import SuccessReply  
from werobot.replies import TextReply
from expiringdict import ExpiringDict

robot = werobot.WeRoBot()

class RobotConfig(object):
    HOST = "127.0.0.1"
    PORT = "8080"
    TOKEN = "11111111111"
robot.config.from_object(RobotConfig)

# 假设这是一个耗时长的任务
def longtime_reply():
    time.sleep(7)
    return "hello world"

cache = ExpiringDict(max_len=100, max_age_seconds=50) # 创建一个缓存,并设置最大长度和最大过期时间

@robot.text
def replyTest(msg):
    usrFromId = msg.source # 用户ID
    recMsg = msg.content  # 用户发来的消息
    try:
        if usrFromId in cache:
            if cache[usrFromId] != "":
                print("这里是38行")
                reply = TextReply(message=msg, content=cache[usrFromId])
                return reply # 将缓存内容发送给微信客户端
            else:
                time.sleep(5)
                print("这里是42行")
                return SuccessReply()
        else:
            cache[usrFromId]= ""
            print("这里是47行")
            content = longtime_reply() # 模拟耗时间长做的任务
            cache[usrFromId]= content # 将拿到耗时间长做的任务结果
            time.sleep(5)
            reply = TextReply(message=msg, content=content)
            print("这里是51行","拿到了结果",content)
            return SuccessReply()
    except Exception as e:
        return e
    # return SuccessReply(

robot.run()

在这里插入图片描述

在这里插入图片描述

第二种方法

from functools import lru_cache

@lru_cache(maxsize=256)
def longtime_reply():
    time.sleep(7)
    return "hello world"


@robot.text
def replyTest(msg):
    usrFromId = msg.source # 用户ID
    recMsg = msg.content  # 用户发来的消息
    print(recMsg)
    return longtime_reply()

两种办法都可以

  • 11
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值