🎯 标题:手把手教你用 FastAPI 搭建一个“大爷级”Web服务 —— 从零开始的实战入门


👋 大家好,我是你们的代码搬运工兼 FastAPI 爱好者。

今天,我们不谈理论,不讲概念,直接上手写一个 FastAPI 项目 —— 从路由、模板、静态文件到“大爷登录”,一步到位,让你快速掌握 FastAPI 的核心玩法!


🧩 项目结构一览

我们先来看一下这个项目的“骨架”:

1
2
3
4
5
6
your_project/
├── main.py # 主程序入口
├── chapter02/
├── templates/
│ └── index.html # HTML模板
└── static/ # 静态资源(CSS/JS/图片等)

是不是很清爽?FastAPI 就是这么简单直接!


🚀 代码逐行解析

1️⃣ 导入与初始化

1
2
3
4
5
6
7
8
#!/usr/bin/env python
# coding=utf-8
from fastapi import FastAPI
import pathlib
from fastapi import Request
from fastapi.responses import HTMLResponse, PlainTextResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
  • FastAPI:核心框架。
  • pathlib:用于路径操作,比 os.path 更现代。
  • Request:获取请求对象。
  • HTMLResponse / PlainTextResponse:返回不同格式的响应。
  • Jinja2Templates:渲染 HTML 模板。
  • StaticFiles:托管静态文件。

2️⃣ 创建 App 实例

1
2
3
4
5
6
app = FastAPI(
title="学习Fastapi框架文档",
description="以下是关于Fastapi框架文档介绍和描述",
version="0.0.1",
debug=True
)

这里我们设置了 API 文档的标题、描述、版本,还开启了调试模式 —— 方便开发时查看错误。

✅ 小贴士:访问 http://127.0.0.1:65535/docs 就能看到自动生成的 Swagger UI 文档!


3️⃣ 配置模板与静态文件

1
2
3
templates = Jinja2Templates(directory=f"{pathlib.Path.cwd()}/chapter02/templates/")
staticfiles = StaticFiles(directory=f"{pathlib.Path.cwd()}/chapter02/static/")
app.mount("/static", staticfiles, name="static")
  • Jinja2Templates:指定模板目录,支持动态渲染。
  • StaticFiles + app.mount:把 /static 路径挂载到静态资源目录,这样你就能访问 /static/css/style.css 之类的文件了。

4️⃣ 主页路由(支持 GET/POST)

1
2
3
4
5
@app.get('/', response_class=HTMLResponse)
@app.get('/index', response_class=HTMLResponse)
@app.post('/index', response_class=HTMLResponse)
async def index(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
  • 三个装饰器,三个路径,一个函数 —— 支持根路径 //index,同时支持 GETPOST 请求。
  • 返回的是 TemplateResponse,即渲染后的 HTML 页面。
  • 别忘了传入 {"request": request} —— 这是 Jinja2 的要求!

5️⃣ “另类”路由注册方式

1
2
3
4
def myinex():
return {"Hello": "myinex api"}

app.get("/myindex", tags=["路由注册方式"], summary="路由注册方式说明")(myinex)

这不是装饰器写法,而是函数式注册路由 —— 适合动态注册或插件化开发。

  • tags:在 API 文档中分组显示。
  • summary:接口的简短说明。

访问 /myindex,你会看到:

1
{ "Hello": "myinex api" }

6️⃣ 终极彩蛋:大爷登录接口 👴

1
2
3
@app.route('/loginjig', methods=['GET', 'POST'], name='loginjig')
def loginjig(req: Request):
return PlainTextResponse('大爷')

注意:这里用了 @app.route —— 这是 Flask 风格的写法,在 FastAPI 中并不推荐!

FastAPI 官方推荐使用 @app.get@app.post 等明确方法的装饰器。

但这段代码能跑吗?不能!

⚠️ 重要提醒@app.route 是 Flask 的语法,FastAPI 不支持!如果你运行这段代码,会报错:

AttributeError: ‘FastAPI’ object has no attribute ‘route’

正确写法应该是:

1
2
3
4
@app.get('/loginjig', name='loginjig')
@app.post('/loginjig', name='loginjig')
async def loginjig(req: Request):
return PlainTextResponse('大爷')

这样,无论 GET 还是 POST,访问 /loginjig 都会返回两个字:

大爷

(别问为什么,问就是“尊重大爷” 😎)


7️⃣ 启动服务

1
2
3
if __name__ == '__main__':
import uvicorn
uvicorn.run(app='main:app', host="127.0.0.1", port=65535, reload=True)
  • uvicorn:ASGI 服务器,专为 FastAPI 优化。
  • reload=True:开发时自动重载,改代码不用重启服务。
  • port=65535:端口号有点大,建议改用 8000,避免被防火墙拦截。

📌 总结:FastAPI 的魅力在哪?

  1. 自动文档:无需额外配置,访问 /docs 即可看到交互式 API 文档。
  2. 类型安全:基于 Python 类型提示,开发更规范,错误更少。
  3. 高性能:基于 Starlette + Pydantic,异步支持,速度飞快。
  4. 灵活路由:装饰器、函数式注册都支持。
  5. 生态丰富:模板、静态文件、中间件、依赖注入一应俱全。

🧑‍💻 给初学者的建议

  • ✅ 用 @app.get / @app.post,别用 @app.route
  • ✅ 模板记得传 request
  • ✅ 静态文件用 app.mount 挂载
  • ✅ 开发时开启 reload=True
  • ✅ 多用 tagssummary,让你的 API 文档更专业

💬 最后说一句

虽然我们最后返回的是“大爷”,但 FastAPI 绝对不是“大爷框架” —— 它年轻、高效、现代,是 Python Web 开发的新宠!

赶紧 clone 代码跑起来,给你的项目也加个“大爷接口”吧 👴