FastAPI 如何将后端和前端结合在一起 – 从 FastAPI 后端端点返回 React 前端

FastAPI 如何将后端和前端结合在一起 – 从 FastAPI 后端端点返回 React 前端

在本文中,我们将介绍如何使用 FastAPI 将后端和前端结合在一起,并从 FastAPI 后端端点返回 React 前端。

阅读更多:FastAPI 教程

什么是 FastAPI

FastAPI 是一个现代、快速(高性能)的 Web 框架,用于构建 API。它是基于 Python 类型提示的(这是 Python 3.6+ 的新功能),并利用了 Python 类型检查的所有优势。通过使用 FastAPI,我们可以轻松地构建高性能的 Web API,并且支持自动生成交互式 API 文档。它还提供了异步支持,可以轻松处理大量并发请求。

创建 React 前端

首先,我们需要创建一个 React 前端项目。我们可以使用 Create React App (https://create-react-app.dev/) 或任何其他喜欢的脚手架工具来创建 React 项目。

以下是通过 Create React App 创建 React 项目的步骤:

  1. 安装 Create React App:
npx create-react-app frontend
Python
  1. 进入项目目录:
cd frontend
Python
  1. 启动开发服务器:
npm start
Python

这样,我们就成功创建了一个简单的 React 前端项目。

创建 FastAPI 后端

接下来,我们需要创建一个 FastAPI 后端项目。

  1. 首先,确保已安装 FastAPI:
pip install fastapi
Python
  1. 创建一个名为 main.py 的文件,并将以下代码复制到文件中:
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()

app.mount("/static", StaticFiles(directory="frontend/build/static"), name="static")

@app.get("/")
def root():
    return {"message": "Hello World"}
Python
  1. 启动 FastAPI 服务器:
uvicorn main:app --reload
Python

这样,我们就成功创建了一个简单的 FastAPI 后端项目。现在,我们将配置 FastAPI 以从后端返回 React 前端。

将 React 前端添加到 FastAPI 后端

为了能够从 FastAPI 后端返回 React 前端,我们需要在 FastAPI 的 main.py 文件中配置静态文件和模板。

首先,我们需要将 React 构建文件夹的路径添加到 FastAPI 的静态文件目录。我们可以使用 FastAPI 的 StaticFiles 中间件来完成这个任务。在上面的示例代码中,我们将 React 构建文件夹的路径设置为 frontend/build

from fastapi.staticfiles import StaticFiles

app.mount("/static", StaticFiles(directory="frontend/build/static"), name="static")
Python

接下来,我们需要将 React 构建文件夹路径的 index.html 文件用作 FastAPI 的模板。

在 FastAPI 中,我们可以使用 Jinja2 模板引擎来生成 HTML 页面。为了使用 Jinja2 模板引擎,我们需要在 FastAPI 的 main.py 文件中添加以下代码:

from fastapi.templating import Jinja2Templates

templates = Jinja2Templates(directory="frontend/build")
Python

然后,我们可以在 FastAPI 的路由处理程序中使用 templates.TemplateResponse 来返回 React 前端的 index.html 文件。以下是一个示例路由处理程序:

from fastapi import Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates

templates = Jinja2Templates(directory="frontend/build")

@app.get("/")
def root(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})
Python

现在,当我们访问 FastAPI 的根端点时,将返回 React 前端的界面。

总结

通过本文,我们学习了如何使用 FastAPI 将后端和前端结合在一起,并从 FastAPI 的后端端点返回 React 前端。我们创建了一个简单的 React 前端项目和一个 FastAPI 后端项目,并配置了 FastAPI 以从后端返回 React 前端。这可以让我们轻松构建现代化的 Web 应用程序,同时享受 FastAPI 的高性能和自动生成的 API 文档的好处。

希望本文对你理解如何将后端和前端结合在一起以及使用 FastAPI 的方法有所帮助!

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册