From 78419c0d33f41902c3c1815c8524c9d45d4aaf67 Mon Sep 17 00:00:00 2001 From: linghaihui <75124771@qq.com> Date: Wed, 29 Mar 2023 09:05:33 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E4=BC=9A=E8=AF=9D=E8=BF=87?= =?UTF-8?q?=E6=9C=9F=E5=88=A4=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- new-bing/app.py | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/new-bing/app.py b/new-bing/app.py index 74b2f05..893003e 100644 --- a/new-bing/app.py +++ b/new-bing/app.py @@ -1,20 +1,18 @@ # coding=utf-8 import json as raw_json -import logging import os import re import threading +from datetime import datetime, timedelta import requests from sanic import Sanic +from sanic.log import logger from sanic.response import json from EdgeGPT import Chatbot, ConversationStyle -logger = logging.getLogger(__name__) -logger.setLevel(logging.INFO) - APPID = os.environ.get('WXAPPID') APPSECRET = os.environ.get('WXAPPSECRET') WX_URL = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code' @@ -31,7 +29,7 @@ app = Sanic('new-bing') app.config.REQUEST_TIMEOUT = 900 app.config.RESPONSE_TIMEOUT = 900 app.config.WEBSOCKET_PING_INTERVAL = 15 -app.config.WEBSOCKET_PING_TIMEOUT = 15 +app.config.WEBSOCKET_PING_TIMEOUT = 30 def reset_cookie(): @@ -67,7 +65,7 @@ async def ws_chat(_, ws): while True: try: data = raw_json.loads(await ws.recv()) - logger.warn('Receive data: %s', data) + logger.info('Websocket receive data: %s', data) sid = data['sid'] q = data['q'] async for response in get_bot(sid).ask_stream(q, conversation_style=ConversationStyle.creative): @@ -96,18 +94,23 @@ async def ws_chat(_, ws): def get_bot(sid): - BOT_LOCK.acquire(timeout=5) + BOT_LOCK.acquire(timeout=2) if sid in bots: BOT_LOCK.release() - return bots[sid] + record = bots[sid] + if record['expired'] > datetime.now(): + return record['bot'] bot = Chatbot() - bots[sid] = bot + bots[sid] = { + 'bot': bot, + 'expired': datetime.now() + timedelta(hours=5, minutes=55), # 会话有效期为6小时 + } BOT_LOCK.release() return bot async def do_chat(request): - logger.warn('Request payload: %s', request.json) + logger.info('Http request payload: %s', request.json) return await get_bot(request.json.get('sid')).ask( request.json.get('q'), conversation_style=ConversationStyle.creative )