目录
安装fnm(PowerShell), 参考 /frontend/README.md
Full Stack FastAPI Template 是一个基于 FastAPI 框架的现代全栈开发模板,集成了后端、前端及数据库等组件,旨在提升开发效率与质量。
1 环境
python 3.12.4
Postgresql, 需安装扩展: uuid-ossp, vector
1.1 安装工具链
# copier
# 该代理代理,该镜像镜像
pip install copier
# 复制并初始化项目
copier copy https://github.com/fastapi/full-stack-fastapi-template my-awesome-project --trust
# UV
# linux
curl -LsSf https://astral.sh/uv/install.sh | sh
# windows
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
# cnpm
# 需设置终端下的代理后使用npm, 安装国内版的cnpm
npm install cnpm -g --registry=https://registry.npm.taobao.org
2 应用安装
2.1 配置
在项目/.env下定义第一个用户的用密,数据库等配置。
2.1 后端
参考项目 /backend/README.md
# 安装项目的python .venv
$ cd backend/
$ uv sync
# linux下激活环境
$ source .venv/bin/activate
# vscode下选择 backend/.venv/Scripts/python.exe
系统初始化脚本:backend/scripts/backend_pre_start.py
如果是linux下则直接运行,win下则改成.bat或手动逐条运行里面的命令
- 初始化基本表与用户数据
启动backend app
cd backend
fastapi run --reload app/main.py
- 修改model并应用到数据库
# 编辑backend\app\models.py, 新增username, nickname
class UserBase(SQLModel):
username: str | None = Field(default=None, index=True, max_length=255)
nickname: str | None = Field(default=None, max_length=255)
email: EmailStr = Field(unique=True, index=True, max_length=255)
is_active: bool = True
is_superuser: bool = False
full_name: str | None = Field(default=None, max_length=255)
# 用alembic产生修改版本
cd .\backend\
alembic revision --autogenerate -m "add user info"
# 把SQLModel模型应用到数据库到最新版本
alembic upgrade head
注:
- 如遇到错误,可删除新产生的版本文件(路径:albembic/versions/{new-version}.py)后再重来
- 如成功后想undo, 用alembic downgrade -1 回退到上一个版本
- 启动
fastapi run --reload .\app\main.py
修改启动文件,用typer shell app包装:
import sentry_sdk
from fastapi import FastAPI
from fastapi.routing import APIRoute
from starlette.middleware.cors import CORSMiddleware
import uvicorn
from app.api.main import api_router
from app.core.config import settings
import typer
shell_app = typer.Typer()
def create_app():
def custom_generate_unique_id(route: APIRoute) -> str:
return f"{route.tags[0]}-{route.name}"
if settings.SENTRY_DSN and settings.ENVIRONMENT != "local":
sentry_sdk.init(dsn=str(settings.SENTRY_DSN), enable_tracing=True)
app = FastAPI(
title=settings.PROJECT_NAME,
openapi_url=f"{settings.API_V1_STR}/openapi.json",
generate_unique_id_function=custom_generate_unique_id,
)
# Set all CORS enabled origins
if settings.all_cors_origins:
app.add_middleware(
CORSMiddleware,
allow_origins=settings.all_cors_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(api_router, prefix=settings.API_V1_STR)
return app
@shell_app.command()
def run(
host: str = typer.Option(
default="0.0.0.0", help="监听主机IP,默认开放给本网络所有主机"
),
port: int = typer.Option(default=8000, help="监听端口"),
):
"""
启动项目
factory: 在使用 uvicorn.run() 启动 ASGI 应用程序时,可以通过设置 factory 参数来指定应用程序工厂。
应用程序工厂是一个返回 ASGI 应用程序实例的可调用对象,它可以在启动时动态创建应用程序实例。
"""
print(f"启动项目:{settings.PROJECT_NAME}")
uvicorn.run(
app="main:create_app",
host=host,
port=port,
lifespan="on",
factory=True,
reload=True,
workers=1,
)
if __name__ == "__main__":
shell_app()
定义调试启动文件: VSCode (Run > Add Configuration) : launch.json
实际命令行是: python .\app\main.py --host 0.0.0.0 --port 8000
- 应用相关
配置文件
路径 | 备注 |
src/backend/app/core/config.py | 主配置文件, 含Settings设置类 |
src/.env | 环境/数据库 参数变量 |
2.2 前端
安装fnm(PowerShell), 参考 /frontend/README.md
winget install Schniz.fnm
使用fnm
fnm install
# 设置环境
fnm env --use-on-cd --shell powershell | Out-String | Invoke-Expression
# 安装npm包
npm install
启动
npm run dev
仪表盘Dashboard
2.3 VSCode 配置调试
包含了应用的前后台启动配置,launch.json
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Backend Server",
"type": "debugpy",
"request": "launch",
"module": "uvicorn",
"args": [
"app.main:app",
"--reload"
],
"cwd": "${workspaceFolder}/backend",
"jinja": true,
"envFile": "${workspaceFolder}/.env",
},
{
"name": "Launch Typer App",
"type": "debugpy",
"request": "launch",
"cwd": "${workspaceFolder}/backend",
"program": "app/main_typer.py",
"args": [
"--host",
"0.0.0.0",
"--port",
"8000"
],
"envFile": "${workspaceFolder}/.env",
"console": "integratedTerminal",
"justMyCode": true
},
{
"name": "Frontend Server",
"type": "node-terminal",
"cwd": "${workspaceFolder}/frontend",
"command": "npm run dev",
"request": "launch"
},
{
"name": "Opener Browser against http://localhost:5173",
"type": "chrome",
"request": "launch",
"url": "http://localhost:5173",
"webRoot": "${workspaceFolder}/frontend",
"runtimeArgs": [
"--do-not-de-elevate"
],
},
]
}
提示
- fastapi 结合request来解析注解参数的实现
参考backend\.venv\Lib\site-packages\fastapi\dependencies\utils.py,solve_dependencies() 方法。