from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates import os import datetime from pydantic import BaseModel import uvicorn from fastapi.middleware.cors import CORSMiddleware # Create FastAPI app app = FastAPI(title="FastAPI Web App") # Add CORS middleware app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Ensure templates directory exists os.makedirs('templates', exist_ok=True) # Set up templates templates = Jinja2Templates(directory="templates") # Create a simple HTML template if it doesn't exist if not os.path.exists('templates/index.html'): os.makedirs('templates', exist_ok=True) with open('templates/index.html', 'w') as f: f.write(''' FastAPI Web App on Hugging Face Spaces

Welcome to FastAPI Web App on Hugging Face Spaces

The current server time is: {{ current_time }}

API Demo

Results will appear here...
''') @app.get("/", response_class=HTMLResponse) async def index(request: Request): """Render the home page.""" current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") return templates.TemplateResponse("index.html", {"request": request, "current_time": current_time}) @app.get("/api/time") async def get_time(): """API endpoint that returns the current time.""" current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") return {"time": current_time} class EchoRequest(BaseModel): """Model for the echo request body.""" message: str = None timestamp: str = None @app.post("/api/echo") async def echo(data: EchoRequest): """API endpoint that echoes back the JSON data sent to it.""" return {"status": "success", "echo": data.dict()} # For local development if __name__ == '__main__': uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=True)