使用 FastAPI 和 Discord 整合建立聯絡表單後端
本教學示範使用 FastAPI 建立強大且安全的後端 API 來管理聯絡表單提交並透過 Webhooks 將其轉發到 Discord 通道。 我們還將解決關鍵的 CORS 配置以實現受控存取。
先決條件:
- Python 3.11
- FastAPI
- httpx(用於非同步 HTTP 請求)
- Discord webhook URL
第 1 步:項目設定
建立專案目錄並安裝必要的套件:
pip install fastapi uvicorn httpx python-dotenv
第 2 步:建立 FastAPI 應用程式
建立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=["*"], )
第 3 步:資料模型定義
使用 Pydantic 進行資料結構:
class FormData(BaseModel): name: str email: str message: str service: str companyName: str companyUrl: str
第 4 步:提交端點
新增表單提交處理程序:
@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))
第 5 步:環境變數
建立.env
檔案:
<code>FASTAPI_DISCORD_WEBHOOK_URL=your_discord_webhook_url_here</code>
工作原理:
- 安全性 CORS: 將對 API 的存取限制為僅授權網域。
- 資料驗證: Pydantic 確保資料完整性。
- 非同步 Discord 整合: 有效率地將訊息傳送到 Discord。
- 強大的錯誤處理:提供資訊豐富的錯誤回應。
運行應用程式:
uvicorn main:app --reload
存取 API http://localhost:8000
。
安全最佳實務:
- 限制 CORS: 僅允許必要的域。
- 環境變數:安全儲存敏感資訊。
- 輸入驗證:始終驗證使用者輸入。
- 全面的錯誤處理:避免暴露敏感細節。
前端整合範例:
fetch('your_api_url/submit', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ /* form data */ }) });
結論:
這個安全的 FastAPI 後端提供了一種可靠且高效的方法來處理聯絡表單並與 Discord 整合。 使用非同步操作和強大的錯誤處理可確保高效能和安全的解決方案。
代碼:https://www.php.cn/link/d92d7ec47187a662aacda2d4b4c7628e 直播:https://www.php.cn/link/775bc655c77d679c193f1982dac04668
以上是使用 FastAPI 和 Discord 整合建立聯絡表單後端的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

使用FiddlerEverywhere進行中間人讀取時如何避免被檢測到當你使用FiddlerEverywhere...

如何在10小時內教計算機小白編程基礎?如果你只有10個小時來教計算機小白一些編程知識,你會選擇教些什麼�...

攻克Investing.com的反爬蟲策略許多人嘗試爬取Investing.com(https://cn.investing.com/news/latest-news)的新聞數據時,常常�...

Python3.6環境下加載pickle文件報錯:ModuleNotFoundError:Nomodulenamed...

使用Scapy爬蟲時管道文件無法寫入的原因探討在學習和使用Scapy爬蟲進行數據持久化存儲時,可能會遇到管道文�...
