Asyncio使用另一个协同程序并发运行Dash(Flask)服务器 [英] Asyncio run Dash (Flask) server with another coroutine concurrently

查看:32
本文介绍了Asyncio使用另一个协同程序并发运行Dash(Flask)服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个Dash应用程序来显示其他代码正在收集的信息,我希望使用Python中的Asyncio模块同时运行这两个应用程序。

我的代码使用的是异步函数,而Dash应用程序(基于FlaskTM)在服务时阻止执行任何其他内容。

我不确定这是否是必须要打开更多线程的事情。

这是我的当前代码,它只运行主协程。

async def main():
    some code here...

    while True:
        try:
            await client.handle_message()
        except ConnectionClosedError as error:
            logger.error(error)
    
        for strategy in strategies:
            await asyncio.create_task(...)
            some code here...

async def run_dashboard():
    app = create_app()
    app.run_server('0.0.0.0', 5000, debug=False)


if __name__ == '__main__':
    some code here...

    # Currently just runs the main coroutine
    asyncio.run(main())

如何同时运行Main和Run_Dashboard?

推荐答案

坦率地讲,将Dash(FlASK)和一些异步工作结合在一个进程中是不好的设计,考虑在不同的进程(即应用程序)中运行FlASK和异步活动。

不过,如果您仍然想在一个进程中运行所有程序,我可以给您提供以下工作示例,请关注评论并询问您是否有任何问题:

from flask import Flask, jsonify
import asyncio
from threading import Thread

# ** Async Part **


async def some_print_task():
    """Some async function"""
    while True:
        await asyncio.sleep(2)
        print("Some Task")


async def another_task():
    """Another async function"""
    while True:
        await asyncio.sleep(3)
        print("Another Task")


async def async_main():
    """Main async function"""
    await asyncio.gather(some_print_task(), another_task())


def async_main_wrapper():
    """Not async Wrapper around async_main to run it as target function of Thread"""
    asyncio.run(async_main())

# *** Flask Part ***:


app = Flask(__name__)


@app.route("/", methods=["GET"])
def index():
    """just some function"""
    return jsonify({"hello": "world"})


if __name__ == '__main__':
    # run all async stuff in another thread
    th = Thread(target=async_main_wrapper)
    th.start()
    # run Flask server
    app.run(host="0.0.0.0", port=9999)
    th.join()

这篇关于Asyncio使用另一个协同程序并发运行Dash(Flask)服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆