搜索
首页后端开发Python教程使用 FastAPI 和 Discord 集成构建联系表单后端

Building a Contact Form Backend with FastAPI and Discord Integration

本教程演示使用 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>

工作原理:

  1. 安全 CORS: 将对 API 的访问限制为仅授权域。
  2. 数据验证: Pydantic 确保数据完整性。
  3. 异步 Discord 集成: 高效地将消息发送到 Discord。
  4. 强大的错误处理:提供信息丰富的错误响应。

运行应用程序:

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中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Python中的合并列表:选择正确的方法Python中的合并列表:选择正确的方法May 14, 2025 am 12:11 AM

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

如何在Python 3中加入两个列表?如何在Python 3中加入两个列表?May 14, 2025 am 12:09 AM

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

Python串联列表字符串Python串联列表字符串May 14, 2025 am 12:08 AM

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

Python执行,那是什么?Python执行,那是什么?May 14, 2025 am 12:06 AM

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

Python:关键功能是什么Python:关键功能是什么May 14, 2025 am 12:02 AM

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

Python:编译器还是解释器?Python:编译器还是解释器?May 13, 2025 am 12:10 AM

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

python用于循环与循环时:何时使用哪个?python用于循环与循环时:何时使用哪个?May 13, 2025 am 12:07 AM

useeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.ForloopSareIdeAlforkNownsences,而WhileLeleLeleLeleLoopSituationSituationSituationsItuationSuationSituationswithUndEtermentersitations。

Python循环:最常见的错误Python循环:最常见的错误May 13, 2025 am 12:07 AM

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

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

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

热门文章

热工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

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

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具