本教程演示使用 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中文网其他相关文章!

Tomergelistsinpython,YouCanusethe操作员,estextMethod,ListComprehension,Oritertools

在Python3中,可以通过多种方法连接两个列表:1)使用 运算符,适用于小列表,但对大列表效率低;2)使用extend方法,适用于大列表,内存效率高,但会修改原列表;3)使用*运算符,适用于合并多个列表,不修改原列表;4)使用itertools.chain,适用于大数据集,内存效率高。

使用join()方法是Python中从列表连接字符串最有效的方法。1)使用join()方法高效且易读。2)循环使用 运算符对大列表效率低。3)列表推导式与join()结合适用于需要转换的场景。4)reduce()方法适用于其他类型归约,但对字符串连接效率低。完整句子结束。

pythonexecutionistheprocessoftransformingpypythoncodeintoExecutablestructions.1)InternterPreterReadSthecode,ConvertingTingitIntObyTecode,whepythonvirtualmachine(pvm)theglobalinterpreterpreterpreterpreterlock(gil)the thepythonvirtualmachine(pvm)

Python的关键特性包括:1.语法简洁易懂,适合初学者;2.动态类型系统,提高开发速度;3.丰富的标准库,支持多种任务;4.强大的社区和生态系统,提供广泛支持;5.解释性,适合脚本和快速原型开发;6.多范式支持,适用于各种编程风格。

Python是解释型语言,但也包含编译过程。1)Python代码先编译成字节码。2)字节码由Python虚拟机解释执行。3)这种混合机制使Python既灵活又高效,但执行速度不如完全编译型语言。

useeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.ForloopSareIdeAlforkNownsences,而WhileLeleLeleLeleLoopSituationSituationSituationsItuationSuationSituationswithUndEtermentersitations。

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐个偏置,零indexingissues,andnestedloopineflinefficiencies


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

Dreamweaver CS6
视觉化网页开发工具

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

WebStorm Mac版
好用的JavaScript开发工具