from fastapi import FastAPI, Form, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse, HTMLResponse from fastapi.staticfiles import StaticFiles import csv import os app = FastAPI() # Enable CORS for frontend-backend communication app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], ) # CSV file to store submissions CSV_FILE = "submissions.csv" # Create CSV with headers if it doesn't exist if not os.path.exists(CSV_FILE): with open(CSV_FILE, "w", newline="") as f: writer = csv.writer(f) writer.writerow(["Full Name", "Phone", "Email", "State", "LGA", "Gender", "Address"]) # Mount static files (JS, CSS, etc.) app.mount("/static", StaticFiles(directory="static"), name="static") # Serve the HTML form @app.get("/", response_class=HTMLResponse) async def get_form(): with open("index.html", "r", encoding="utf-8") as f: html_content = f.read() return HTMLResponse(content=html_content) # Handle form submissions @app.post("/submit/") async def submit_form( fullname: str = Form(...), phone: str = Form(...), email: str = Form(...), state: str = Form(...), lga: str = Form(...), gender: str = Form(...), address: str = Form(...) ): with open(CSV_FILE, "a", newline="") as f: writer = csv.writer(f) writer.writerow([fullname, phone, email, state, lga, gender, address]) return {"message": "Submission received"} # Endpoint to download all submissions @app.get("/submissions/") def get_submissions(): return FileResponse(CSV_FILE, media_type="text/csv", filename="stc_submissions.csv")