docs: add comments
This commit is contained in:
24
main.py
24
main.py
@@ -6,33 +6,43 @@ from fastapi.responses import StreamingResponse
|
|||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
import datetime
|
import datetime
|
||||||
|
|
||||||
|
# Use of Pydantic class for automatic request validation in FastAPI
|
||||||
class Message(BaseModel):
|
class Message(BaseModel):
|
||||||
message: str
|
message: str
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
|
# This middleware allows other origins to communicate with us
|
||||||
app.add_middleware(
|
app.add_middleware(
|
||||||
CORSMiddleware,
|
CORSMiddleware, # https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS
|
||||||
allow_origins=["http://localhost:5173"],
|
allow_origins=["http://localhost:5173"], # address of our UI application
|
||||||
allow_credentials=True,
|
allow_methods=["*"], # GET, POST, etc.
|
||||||
allow_methods=["*"],
|
|
||||||
allow_headers=["*"],
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Endpoint to receive messages from the UI
|
||||||
@app.post("/message")
|
@app.post("/message")
|
||||||
async def receive_message(message: Message):
|
async def receive_message(message: Message):
|
||||||
|
"""
|
||||||
|
Receives a message from the UI and prints it to the console.
|
||||||
|
"""
|
||||||
print(f"Received message: {message}")
|
print(f"Received message: {message}")
|
||||||
return { "status": "Message received" }
|
return { "status": "Message received" }
|
||||||
|
|
||||||
|
# Endpoint for Server-Sent Events (SSE)
|
||||||
@app.get("/sse")
|
@app.get("/sse")
|
||||||
async def sse_endpoint(request: Request):
|
async def sse_endpoint(request: Request):
|
||||||
|
"""
|
||||||
|
Endpoint for Server-Sent Events.
|
||||||
|
"""
|
||||||
async def event_generator():
|
async def event_generator():
|
||||||
while True:
|
while True:
|
||||||
|
# If connection to client closes, stop sending events
|
||||||
if await request.is_disconnected():
|
if await request.is_disconnected():
|
||||||
break
|
break
|
||||||
|
|
||||||
|
# Send message containing current time every second
|
||||||
current_time = datetime.datetime.now().strftime("%H:%M:%S")
|
current_time = datetime.datetime.now().strftime("%H:%M:%S")
|
||||||
yield f"data: Server time: {current_time}\n\n"
|
yield f"data: Server time: {current_time}\n\n" # \n\n is needed to separate events (SSE is text-based)
|
||||||
await asyncio.sleep(1)
|
await asyncio.sleep(1)
|
||||||
|
|
||||||
return StreamingResponse(event_generator(), media_type="text/event-stream")
|
return StreamingResponse(event_generator(), media_type="text/event-stream") # media_type specifies that this connection is for event streams
|
||||||
|
|||||||
Reference in New Issue
Block a user