I want to run a quart server alongside other coroutines. However, it seems that the server is blocking the event loop. The server responds to the requests, but neither the timing routine nor the queue processing routine are running.
import quart
import asyncio
import signal
import random
q = asyncio.Queue()
app = quart.Quart(__name__)
async def run_timer(start=0):
global q
i = start
while True:
print(f"Current value: {i}")
await asyncio.sleep(2)
i += 1
async def process_queue():
global q
print("Start queue processing")
while True:
val = await q.get()
print(f"Queue: {val}")
# Simulate blocking operation
time.sleep(random.random())
@app.route('/add', methods=['POST'])
async def add():
global q
print(await quart.request.get_data())
values = await quart.request.form
print(f"Request: {dict(values)}")
if 'message' in values:
q.put_nowait(values['message'])
return 'Request received'
async def main():
tasks = [run_timer(0), process_queue(), app.run_task(port=8080,use_reloader=False)]
await asyncio.gather(*tasks)
asyncio.run(main())
Output:
Current value: 0
Start queue processing
[2021-08-14 12:51:49,541] Running on http://127.0.0.1:8080 (CTRL + C to quit)
Request: {'message': 'test'}
[2021-08-14 12:51:51,837] 127.0.0.1:59990 POST /add 1.1 200 16 1526
The message is sent with curl -d 'message=test' LOCAlhost:8080/add
It would also be nice to stop all coroutines on SIGTERM