streamableHTTP / app.py
Almaatla's picture
Update app.py
2f71be7 verified
# app.py (Server)
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse, HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
import asyncio
import time # Missing import causing NameError
app = FastAPI()
# CORS Configuration
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# Streamable HTTP Endpoint
async def data_streamer():
"""Generates real-time data chunks"""
for i in range(1, 11):
await asyncio.sleep(1)
yield f"data: Chunk {i} - {time.ctime()}\n\n"
@app.get("/stream")
async def stream_data():
return StreamingResponse(
data_streamer(),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache"}
)
# SPA Client Endpoint
@app.get("/", response_class=HTMLResponse)
async def get_spa():
return """
<html>
<head>
<title>Stream Demo</title>
<style>
body { font-family: sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
#output { border: 1px solid #ccc; padding: 20px; margin-top: 20px; }
</style>
</head>
<body>
<h1>Real-time Stream Demo</h1>
<button onclick="startStream()">Start Stream</button>
<div id="output"></div>
<script>
async function startStream() {
const output = document.getElementById('output');
try {
const response = await fetch('/stream');
const reader = response.body.getReader();
const decoder = new TextDecoder();
while(true) {
const { done, value } = await reader.read();
if(done) break;
const chunk = decoder.decode(value);
output.innerHTML += chunk + '<br>';
}
} catch(error) {
output.innerHTML = 'Error: ' + error;
}
}
</script>
</body>
</html>
"""