Untitled

mail@pastecode.io avatar
unknown
plain_text
21 days ago
1.0 kB
2
Indexable
Never
from flask import Flask, Response
import asyncio

app = Flask(__name__)

# Simulate asynchronous checks using asyncio
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 to call checks and stream the result
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 an event loop
@app.route('/stream')
def stream_response():
    async def generate():
        async for result in function_1():
            yield result
    return Response(generate(), content_type='text/event-stream')

if __name__ == '__main__':
    app.run(debug=True)
Leave a Comment