Issue
I created a dash app to present information that another code is collecting, I want to run them both concurrently using the asyncio module in Python.
My code is using async functions and the Dash app (which is based on Flask) is blocking anything else from executing while serving.
I'm not sure if this is something that has to involve opening up more threads.
Here's my current code which only runs the main coroutine.
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())
How can I run main and run_dashboard concurrently?
Solution
Frankly speaking it is not good design to combine Dash (Flask) with some async work in one process, consider to run Flask and async activities in different processes (i.e. apps).
Nevertheless, If you still want to run all in one process, I can give you the following working example, please follow comments and ask if you have any questions:
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()
Answered By - Artiom Kozyrev
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.