Python创建FastApi项目模板

1. 项目结构规范

myproject/
├── app/
│   ├── core/              # 核心配置
│   │   ├── config.py     # 环境配置
│   │   └── security.py   # 安全配置
│   ├── routers/          # 路由模块
│   │   └── users.py      # 用户路由
│   ├── models/           # 数据库模型
│   │   └── user.py       # 用户模型
│   ├── schemas/          # Pydantic模型
│   │   └── user.py       # 用户Schema
│   ├── services/         # 业务逻辑
│   │   └── user.py       # 用户服务
│   ├── dependencies.py   # 依赖注入
│   └── db/               # 数据库配置
├── tests/                # 测试用例
│   └── test_users.py     # 用户测试
├── requirements.txt      # 依赖文件
└── main.py               # 入口文件

2. 核心代码示例

配置管理 (app/core/config.py)
from pydantic import BaseSettings

class Settings(BaseSettings):
    API_V1_STR: str = "/api/v1"
    DB_URL: str = "postgresql+asyncpg://user:pass@localhost:5432/db"
    JWT_SECRET: str = "secret-key"
    
    class Config:
        env_file = ".env"

settings = Settings()
路由示例 (app/routers/users.py)
from fastapi import APIRouter, Depends, HTTPException
from app.services.user import UserService
from app.schemas.user import UserCreate, UserResponse
from app.dependencies import get_db

router = APIRouter(prefix="/users", tags=["users"])

@router.post("/", response_model=UserResponse)
async def create_user(
    user: UserCreate,
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值