Spaces:
Sleeping
Sleeping
from fastapi import FastAPI, HTTPException, Request | |
from fastapi.responses import JSONResponse | |
import os, json | |
app = FastAPI() | |
PROJECTS_DIR = "projects" | |
os.makedirs(PROJECTS_DIR, exist_ok=True) | |
def load_project(project: str): | |
""" | |
GET /load?project=FILENAME | |
Returns the JSON contents of projects/FILENAME | |
""" | |
path = os.path.join(PROJECTS_DIR, os.path.basename(project)) | |
if not os.path.isfile(path): | |
raise HTTPException(status_code=404, detail="Project not found") | |
with open(path, "r", encoding="utf-8") as f: | |
data = json.load(f) | |
return JSONResponse(content=data) | |
async def save_project(project: str, request: Request): | |
""" | |
POST /save?project=FILENAME | |
Body: JSON project data | |
Writes the data back into projects/FILENAME | |
""" | |
body = await request.json() | |
path = os.path.join(PROJECTS_DIR, os.path.basename(project)) | |
with open(path, "w", encoding="utf-8") as f: | |
json.dump(body, f, indent=2) | |
return JSONResponse(content={"success": True}) | |
if __name__ == "__main__": | |
# When you run `python app.py`, this will start Uvicorn on the HF Spaces port. | |
import uvicorn | |
uvicorn.run(app, host="0.0.0.0", port=7860) | |