Spaces:
Sleeping
Sleeping
File size: 2,287 Bytes
217c02a 2f71be7 217c02a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# 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>
"""
|