一、简介
FastAPI 是一款现代、轻量、高性能的 Python Web 框架,专门用于快速构建 API。它是 Python 生态中流行的 Web 框架之一,适合快速上手编写后端接口。
FastAPI 适用场景包括:
- 前后端分离项目的后端 API;
- 微服务间的接口;
- 数据接口(如提供数据库商品信息);
- 快速原型开发。
二、FastAPI+Python 前后端交互解析
1. 前后端交互本质
使用餐厅点餐的比喻理解:
- 前端:顾客,负责提需求;
- 后端:厨房,负责处理需求;
- HTTP 协议:服务员,负责传递需求和结果;
- 请求:顾客喊'来碗牛肉面';
- 响应:服务员端上做好的菜。
Python 前端脚本相当于'顾客',FastAPI 后端相当于'厨房',两者通过 HTTP 协议传递数据。
2. 项目需求
使用 FastAPI 实现以下功能:
- 用户注册:用户名和密码不为空,用户名长度大于 6,密码长度大于 8 且包含下划线、字母和数字时保存数据,不允许重复用户名。
- 用户登录:用户名和密码正确时提示欢迎,否则提示错误。
- 查看用户信息:获取已注册用户列表。
3. 代码设计思路
前端设计思路
使用 requests 库发送 HTTP 请求。
import requests
while True:
user_input = input('1、注册\n2、登录\n3、查看\n4、退出\n请输入你要进行的操作:')
if user_input == '1':
user = input("用户名:")
password = input("密码:")
res = requests.post("http://127.0.0.1:8000/user/register", params={"username": user, "password": password})
result = res.json()
print(f"{result['result']}")
elif user_input == '2':
user = input("用户名:")
password = input()
res = requests.post(, params={: user, : password})
result = res.json()
()
user_input == :
res = requests.post()
result = res.json()
()
user_input == :
:
()

