格式化代码
This commit is contained in:
@@ -7,15 +7,17 @@ from loguru import logger
|
||||
# 创建联系人管理蓝图
|
||||
contacts_bp = Blueprint('contacts', __name__, url_prefix='/contacts')
|
||||
|
||||
|
||||
def send_message_in_thread(func, *args, **kwargs):
|
||||
"""在独立线程中发送消息"""
|
||||
|
||||
def run():
|
||||
loop = None
|
||||
try:
|
||||
# 创建新的事件循环
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
|
||||
|
||||
# 创建异步任务
|
||||
async def send():
|
||||
try:
|
||||
@@ -25,13 +27,13 @@ def send_message_in_thread(func, *args, **kwargs):
|
||||
finally:
|
||||
# 发送完成后停止事件循环
|
||||
loop.stop()
|
||||
|
||||
|
||||
# 创建并运行任务
|
||||
asyncio.run_coroutine_threadsafe(send(), loop)
|
||||
|
||||
|
||||
# 运行事件循环直到停止
|
||||
loop.run_forever()
|
||||
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"线程执行失败: {e}")
|
||||
finally:
|
||||
@@ -42,23 +44,24 @@ def send_message_in_thread(func, *args, **kwargs):
|
||||
pending = asyncio.all_tasks(loop)
|
||||
for task in pending:
|
||||
task.cancel()
|
||||
|
||||
|
||||
# 运行事件循环直到所有任务都被取消
|
||||
loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True))
|
||||
|
||||
|
||||
# 停止事件循环
|
||||
loop.stop()
|
||||
|
||||
|
||||
# 关闭事件循环
|
||||
loop.close()
|
||||
except Exception as e:
|
||||
logger.error(f"清理资源失败: {e}")
|
||||
|
||||
|
||||
# 创建并启动线程
|
||||
thread = threading.Thread(target=run)
|
||||
thread.daemon = True # 设置为守护线程,这样主程序退出时线程会自动结束
|
||||
thread.start()
|
||||
|
||||
|
||||
# 联系人管理页面
|
||||
@contacts_bp.route('/')
|
||||
@login_required
|
||||
|
||||
Reference in New Issue
Block a user