Dieses Tutorial zeigt den Aufbau einer robusten und sicheren Backend-API mithilfe von FastAPI, um die Übermittlung von Kontaktformularen zu verwalten und sie über Webhooks an einen Discord-Kanal weiterzuleiten. Wir werden uns auch mit der wichtigen CORS-Konfiguration für den kontrollierten Zugriff befassen.
Voraussetzungen:
Schritt 1: Projekteinrichtung
Erstellen Sie ein Projektverzeichnis und installieren Sie die erforderlichen Pakete:
pip install fastapi uvicorn httpx python-dotenv
Schritt 2: FastAPI-Anwendungserstellung
Erstellen Sie main.py
:
import os from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel import httpx app = FastAPI() # CORS Configuration (Security!) app.add_middleware( CORSMiddleware, allow_origins=["https://vicentereyes.org", "https://www.vicentereyes.org"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], )
Schritt 3: Datenmodelldefinition
Verwenden Sie Pydantic für die Datenstruktur:
class FormData(BaseModel): name: str email: str message: str service: str companyName: str companyUrl: str
Schritt 4: Übermittlungsendpunkt
Fügen Sie den Formularübermittlungshandler hinzu:
@app.post("/submit/") @app.post("/submit") # Handles both /submit and /submit/ async def submit_form(form_data: FormData): try: # Format message for Discord message_content = { "content": f"New form submission:\n" f"**Name:** {form_data.name}\n" f"**Email:** {form_data.email}\n" f"**Message:** {form_data.message}\n" f"**Service:** {form_data.service}\n" f"**Company Name:** {form_data.companyName}\n" f"**Company URL:** {form_data.companyUrl}" } # Send to Discord webhook using httpx async with httpx.AsyncClient() as client: response = await client.post(os.environ["FASTAPI_DISCORD_WEBHOOK_URL"], json=message_content) if response.status_code != 204: raise HTTPException(status_code=response.status_code, detail="Discord message failed") return {"message": "Form data sent successfully"} except Exception as e: raise HTTPException(status_code=500, detail=str(e))
Schritt 5: Umgebungsvariablen
Erstellen Sie eine .env
Datei:
<code>FASTAPI_DISCORD_WEBHOOK_URL=your_discord_webhook_url_here</code>
Wie es funktioniert:
Ausführen der Anwendung:
uvicorn main:app --reload
Zugriff auf die API unter http://localhost:8000
.
Bewährte Sicherheitspraktiken:
Beispiel für die Frontend-Integration:
fetch('your_api_url/submit', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ /* form data */ }) });
Fazit:
Dieses sichere FastAPI-Backend bietet eine zuverlässige und effiziente Methode zur Bearbeitung von Kontaktformularen und zur Integration mit Discord. Der Einsatz asynchroner Operationen und robuster Fehlerbehandlung gewährleistet eine leistungsstarke und sichere Lösung.
Code: https://www.php.cn/link/d92d7ec47187a662aacda2d4b4c7628e Live: https://www.php.cn/link/775bc655c77d679c193f1982dac04668
Das obige ist der detaillierte Inhalt vonAufbau eines Kontaktformular-Backends mit FastAPI und Discord-Integration. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!