去哪找做网站的人,自己做头像的软件,界面设计的基本原则,wordpress主题快速文章目录 技术栈选择后端技术栈前端技术栈 项目整体结构详细目录结构说明后端架构#xff08;backend/#xff09;1. 应用核心#xff08;app/#xff09;2. 数据层#xff08;models/#xff09;3. API模式层#xff08;schemas/#xff09;4. API路由层#xff08;a… 文章目录 技术栈选择后端技术栈前端技术栈 项目整体结构详细目录结构说明后端架构backend/1. 应用核心app/2. 数据层models/3. API模式层schemas/4. API路由层api/5. 业务逻辑层services/ 前端架构frontend/1. 应用入口app.py2. 页面组件pages/3. 可复用组件components/4. API服务层services/ 关键配置文件1. docker-compose.yml2. 后端Dockerfile3. 前端Dockerfile 开发工作流1. 环境设置2. 开发模式启动3. 生产环境部署 项目优势1. 技术一致性2. 高性能3. 快速开发4. 良好的可扩展性 最佳实践建议1. 代码组织2. 错误处理3. 安全性4. 性能优化 在现代Web开发中前后端分离已成为主流架构模式。本文将详细介绍如何使用纯Python技术栈构建一个完整的前后端分离项目包括项目结构设计、技术选型和最佳实践。
技术栈选择
后端技术栈
框架: FastAPI高性能异步Web框架数据库: PostgreSQL SQLAlchemy ORM缓存: Redis认证: JWT TokenAPI文档: Swagger/OpenAPIFastAPI自带测试: pytest httpx依赖管理: Poetry
前端技术栈
框架: Streamlit 或 Reflex纯Python前端框架状态管理: 内置状态管理HTTP客户端: httpx/requests数据可视化: Plotly Dash可选
项目整体结构
my-python-fullstack-project/
├── README.md
├── docker-compose.yml
├── .env.example
├── .gitignore
├── requirements.txt
├── backend/ # 后端服务
│ ├── app/
│ │ ├── __init__.py
│ │ ├── main.py # FastAPI应用入口
│ │ ├── config.py # 配置文件
│ │ ├── dependencies.py # 依赖注入
│ │ ├── database.py # 数据库连接
│ │ ├── models/ # 数据模型
│ │ │ ├── __init__.py
│ │ │ ├── user.py
│ │ │ ├── product.py
│ │ │ └── base.py
│ │ ├── schemas/ # Pydantic模式
│ │ │ ├── __init__.py
│ │ │ ├── user.py
│ │ │ ├── product.py
│ │ │ └── response.py
│ │ ├── api/ # API路由
│ │ │ ├── __init__.py
│ │ │ ├── deps.py
│ │ │ ├── v1/
│ │ │ │ ├── __init__.py
│ │ │ │ ├── auth.py
│ │ │ │ ├── users.py
│ │ │ │ └── products.py
│ │ │ └── api.py
│ │ ├── crud/ # CRUD操作
│ │ │ ├── __init__.py
│ │ │ ├── base.py
│ │ │ ├── user.py
│ │ │ └── product.py
│ │ ├── core/ # 核心功能
│ │ │ ├── __init__.py
│ │ │ ├── security.py # 安全相关
│ │ │ ├── auth.py # 认证逻辑
│ │ │ └── exceptions.py # 异常处理
│ │ ├── services/ # 业务逻辑层
│ │ │ ├── __init__.py
│ │ │ ├── user_service.py
│ │ │ └── product_service.py
│ │ └── utils/ # 工具函数
│ │ ├── __init__.py
│ │ ├── logger.py
│ │ └── helpers.py
│ ├── alembic/ # 数据库迁移
│ │ ├── versions/
│ │ ├── env.py
│ │ └── alembic.ini
│ ├── tests/ # 测试文件
│ │ ├── __init__.py
│ │ ├── conftest.py
│ │ ├── test_auth.py
│ │ └── test_users.py
│ ├── Dockerfile
│ ├── requirements.txt
│ └── pyproject.toml
├── frontend/ # 前端应用
│ ├── app.py # 主应用文件
│ ├── config.py # 前端配置
│ ├── pages/ # 页面组件
│ │ ├── __init__.py
│ │ ├── home.py
│ │ ├── auth/
│ │ │ ├── __init__.py
│ │ │ ├── login.py
│ │ │ └── register.py
│ │ ├── dashboard/
│ │ │ ├── __init__.py
│ │ │ ├── overview.py
│ │ │ └── analytics.py
│ │ └── products/
│ │ ├── __init__.py
│ │ ├── list.py
│ │ └── detail.py
│ ├── components/ # 可复用组件
│ │ ├── __init__.py
│ │ ├── sidebar.py
│ │ ├── header.py
│ │ └── forms/
│ │ ├── __init__.py
│ │ ├── auth_forms.py
│ │ └── product_forms.py
│ ├── services/ # API服务
│ │ ├── __init__.py
│ │ ├── api_client.py # HTTP客户端封装
│ │ ├── auth_service.py
│ │ └── product_service.py
│ ├── utils/ # 前端工具
│ │ ├── __init__.py
│ │ ├── constants.py
│ │ ├── validators.py
│ │ └── formatters.py
│ ├── static/ # 静态资源
│ │ ├── css/
│ │ ├── js/
│ │ └── images/
│ ├── tests/ # 前端测试
│ │ ├── __init__.py
│ │ └── test_components.py
│ ├── Dockerfile
│ └── requirements.txt
├── shared/ # 共享代码
│ ├── __init__.py
│ ├── constants.py # 共享常量
│ ├── exceptions.py # 共享异常
│ └── utils.py # 共享工具
├── scripts/ # 部署脚本
│ ├── deploy.sh
│ ├── backup.sh
│ └── init_db.py
├── docs/ # 项目文档
│ ├── api.md
│ ├── deployment.md
│ └── development.md
└── nginx/ # Nginx配置└── nginx.conf详细目录结构说明
后端架构backend/
1. 应用核心app/
main.py: FastAPI应用的入口点包含应用初始化、中间件配置和路由注册config.py: 应用配置管理使用Pydantic Settings进行环境变量管理database.py: 数据库连接和会话管理
2. 数据层models/
使用SQLAlchemy定义数据模型每个模型对应一个文件
# models/user.py
from sqlalchemy import Column, Integer, String, Boolean
from .base import Baseclass User(Base):__tablename__ usersid Column(Integer, primary_keyTrue, indexTrue)email Column(String, uniqueTrue, indexTrue)hashed_password Column(String)is_active Column(Boolean, defaultTrue)3. API模式层schemas/
使用Pydantic定义请求和响应模型确保数据验证和API文档生成
# schemas/user.py
from pydantic import BaseModel, EmailStrclass UserCreate(BaseModel):email: EmailStrpassword: strclass UserResponse(BaseModel):id: intemail: stris_active: boolclass Config:from_attributes True4. API路由层api/
按版本和功能模块组织API端点
# api/v1/users.py
from fastapi import APIRouter, Depends
from ...services.user_service import UserServicerouter APIRouter()router.post(/, response_modelUserResponse)
async def create_user(user_data: UserCreate, service: UserService Depends()):return await service.create_user(user_data)5. 业务逻辑层services/
封装复杂的业务逻辑保持控制器的简洁
# services/user_service.py
class UserService:def __init__(self, db: Session Depends(get_db)):self.db dbasync def create_user(self, user_data: UserCreate) - User:# 业务逻辑实现pass前端架构frontend/
1. 应用入口app.py
# app.py
import streamlit as st
from pages.home import show_home
from pages.auth.login import show_logindef main():st.set_page_config(page_titleMy App, layoutwide)# 路由逻辑if authenticated not in st.session_state:show_login()else:show_home()if __name__ __main__:main()2. 页面组件pages/
按功能模块组织页面组件每个页面负责特定的UI逻辑。
3. 可复用组件components/
抽象通用的UI组件提高代码复用性。
4. API服务层services/
封装与后端API的交互逻辑
# services/api_client.py
import httpx
from typing import Optionalclass APIClient:def __init__(self, base_url: str):self.base_url base_urlself.token: Optional[str] Noneasync def request(self, method: str, endpoint: str, **kwargs):headers kwargs.get(headers, {})if self.token:headers[Authorization] fBearer {self.token}async with httpx.AsyncClient() as client:response await client.request(method, f{self.base_url}{endpoint}, headersheaders, **kwargs)return response.json()关键配置文件
1. docker-compose.yml
version: 3.8
services:backend:build: ./backendports:- 8000:8000environment:- DATABASE_URLpostgresql://user:passdb:5432/myapp- REDIS_URLredis://redis:6379depends_on:- db- redisfrontend:build: ./frontendports:- 8501:8501environment:- API_BASE_URLhttp://backend:8000depends_on:- backenddb:image: postgres:13environment:- POSTGRES_DBmyapp- POSTGRES_USERuser- POSTGRES_PASSWORDpassvolumes:- postgres_data:/var/lib/postgresql/dataredis:image: redis:7-alpineports:- 6379:6379volumes:postgres_data:2. 后端Dockerfile
FROM python:3.11-slimWORKDIR /appCOPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txtCOPY . .CMD [uvicorn, app.main:app, --host, 0.0.0.0, --port, 8000]3. 前端Dockerfile
FROM python:3.11-slimWORKDIR /appCOPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txtCOPY . .EXPOSE 8501CMD [streamlit, run, app.py, --server.port8501, --server.address0.0.0.0]开发工作流
1. 环境设置
# 克隆项目
git clone repository-url
cd my-python-fullstack-project# 设置虚拟环境
python -m venv venv
source venv/bin/activate # Linux/Mac
# 或 venv\Scripts\activate # Windows# 安装依赖
pip install -r requirements.txt2. 开发模式启动
# 启动后端
cd backend
uvicorn app.main:app --reload --port 8000# 启动前端新终端
cd frontend
streamlit run app.py --server.port 85013. 生产环境部署
# 使用Docker Compose
docker-compose up -d# 数据库迁移
docker-compose exec backend alembic upgrade head项目优势
1. 技术一致性
前后端都使用Python降低了技术栈的复杂性开发团队只需掌握一种主要编程语言代码共享和维护更加容易
2. 高性能
FastAPI提供了异步支持和高性能自动生成API文档内置数据验证和序列化
3. 快速开发
Streamlit提供了快速构建Web应用的能力丰富的组件库和可视化支持无需前端框架的复杂配置
4. 良好的可扩展性
清晰的分层架构模块化设计易于测试和维护
最佳实践建议
1. 代码组织
遵循单一职责原则使用依赖注入保持接口的一致性
2. 错误处理
统一的异常处理机制友好的错误消息适当的日志记录
3. 安全性
JWT token认证输入验证和清理CORS配置环境变量管理
4. 性能优化
数据库查询优化缓存策略异步处理资源压缩