TestingFastApi / main.py
mohsinramzan's picture
Fixing the CORS Middle Ware
f92a401
Raw History Blame Contribute Delete
977 Bytes
from fastapi import FastAPI, Request
from pydantic import BaseModel
from typing import Dict
import time
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # or set this to your frontend's origin
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# In-memory storage for now
bus_locations: Dict[str, dict] = {}
class Location(BaseModel):
_type: str
tid: str
lat: float
lon: float
tst: int
@app.post("/track")
async def track_location(loc: Location):
# Save by bus_id (tid)
bus_locations[loc.tid] = {
"lat": loc.lat,
"lon": loc.lon,
"timestamp": loc.tst,
"last_updated": time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(loc.tst))
}
print(f"[{loc.tid}] → ({loc.lat}, {loc.lon}) @ {loc.tst}")
return {"status": "ok"}
@app.get("/locations")
def get_all_locations():
return bus_locations