Untitled
unknown
plain_text
a year ago
1.4 kB
9
Indexable
from flask import Flask, Response
import asyncio
app = Flask(__name__)
# Asynchronous versions of check1, check2, check3
async def check1():
await asyncio.sleep(1) # Simulate delay
return "data: Check 1 completed.\n\n"
async def check2():
await asyncio.sleep(1)
return "data: Check 2 completed.\n\n"
async def check3():
await asyncio.sleep(1)
return "data: Check 3 completed.\n\n"
# Main function that calls the async checks
async def function_1():
yield await check1() # Stream check1 result
yield await check2() # Stream check2 result
yield await check3() # Stream check3 result
yield "data: Final processing in function_1 completed.\n\n"
# Synchronous Flask view that runs async code in the event loop
@app.route('/stream')
def stream_response():
# Helper function to run async code synchronously
def generate():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
async_gen = function_1()
# Using event loop to run the async generator
try:
while True:
result = loop.run_until_complete(async_gen.__anext__())
yield result
except StopAsyncIteration:
loop.close()
return Response(generate(), content_type='text/event-stream')
if __name__ == '__main__':
app.run(debug=True)Editor is loading...
Leave a Comment