Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py (Server)
|
| 2 |
+
from fastapi import FastAPI, Request
|
| 3 |
+
from fastapi.responses import StreamingResponse, HTMLResponse
|
| 4 |
+
from fastapi.staticfiles import StaticFiles
|
| 5 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 6 |
+
import asyncio
|
| 7 |
+
|
| 8 |
+
app = FastAPI()
|
| 9 |
+
|
| 10 |
+
# CORS Configuration
|
| 11 |
+
app.add_middleware(
|
| 12 |
+
CORSMiddleware,
|
| 13 |
+
allow_origins=["*"],
|
| 14 |
+
allow_methods=["*"],
|
| 15 |
+
allow_headers=["*"],
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
# Streamable HTTP Endpoint
|
| 19 |
+
async def data_streamer():
|
| 20 |
+
"""Generates real-time data chunks"""
|
| 21 |
+
for i in range(1, 11):
|
| 22 |
+
await asyncio.sleep(1)
|
| 23 |
+
yield f"data: Chunk {i} - {time.ctime()}\n\n"
|
| 24 |
+
|
| 25 |
+
@app.get("/stream")
|
| 26 |
+
async def stream_data():
|
| 27 |
+
return StreamingResponse(
|
| 28 |
+
data_streamer(),
|
| 29 |
+
media_type="text/event-stream",
|
| 30 |
+
headers={"Cache-Control": "no-cache"}
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
# SPA Client Endpoint
|
| 34 |
+
@app.get("/", response_class=HTMLResponse)
|
| 35 |
+
async def get_spa():
|
| 36 |
+
return """
|
| 37 |
+
<html>
|
| 38 |
+
<head>
|
| 39 |
+
<title>Stream Demo</title>
|
| 40 |
+
<style>
|
| 41 |
+
body { font-family: sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
|
| 42 |
+
#output { border: 1px solid #ccc; padding: 20px; margin-top: 20px; }
|
| 43 |
+
</style>
|
| 44 |
+
</head>
|
| 45 |
+
<body>
|
| 46 |
+
<h1>Real-time Stream Demo</h1>
|
| 47 |
+
<button onclick="startStream()">Start Stream</button>
|
| 48 |
+
<div id="output"></div>
|
| 49 |
+
<script>
|
| 50 |
+
async function startStream() {
|
| 51 |
+
const output = document.getElementById('output');
|
| 52 |
+
try {
|
| 53 |
+
const response = await fetch('/stream');
|
| 54 |
+
const reader = response.body.getReader();
|
| 55 |
+
const decoder = new TextDecoder();
|
| 56 |
+
|
| 57 |
+
while(true) {
|
| 58 |
+
const { done, value } = await reader.read();
|
| 59 |
+
if(done) break;
|
| 60 |
+
const chunk = decoder.decode(value);
|
| 61 |
+
output.innerHTML += chunk + '<br>';
|
| 62 |
+
}
|
| 63 |
+
} catch(error) {
|
| 64 |
+
output.innerHTML = 'Error: ' + error;
|
| 65 |
+
}
|
| 66 |
+
}
|
| 67 |
+
</script>
|
| 68 |
+
</body>
|
| 69 |
+
</html>
|
| 70 |
+
"""
|