解决微信客户端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()
两种办法都可以