文章目錄
- 技術棧選擇
- 后端技術棧
- 前端技術棧
- 項目整體結構
- 詳細目錄結構說明
- 后端架構(backend/)
- 1. 應用核心(app/)
- 2. 數據層(models/)
- 3. API模式層(schemas/)
- 4. API路由層(api/)
- 5. 業務邏輯層(services/)
- 前端架構(frontend/)
- 1. 應用入口(app.py)
- 2. 頁面組件(pages/)
- 3. 可復用組件(components/)
- 4. API服務層(services/)
- 關鍵配置文件
- 1. docker-compose.yml
- 2. 后端Dockerfile
- 3. 前端Dockerfile
- 開發工作流
- 1. 環境設置
- 2. 開發模式啟動
- 3. 生產環境部署
- 項目優勢
- 1. 技術一致性
- 2. 高性能
- 3. 快速開發
- 4. 良好的可擴展性
- 最佳實踐建議
- 1. 代碼組織
- 2. 錯誤處理
- 3. 安全性
- 4. 性能優化
在現代Web開發中,前后端分離已成為主流架構模式。本文將詳細介紹如何使用純Python技術棧構建一個完整的前后端分離項目,包括項目結構設計、技術選型和最佳實踐。
技術棧選擇
后端技術棧
- 框架: FastAPI(高性能異步Web框架)
- 數據庫: PostgreSQL + SQLAlchemy ORM
- 緩存: Redis
- 認證: JWT Token
- API文檔: Swagger/OpenAPI(FastAPI自帶)
- 測試: 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__ = "users"id = Column(Integer, primary_key=True, index=True)email = Column(String, unique=True, index=True)hashed_password = Column(String)is_active = Column(Boolean, default=True)
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 = True
4. API路由層(api/)
按版本和功能模塊組織API端點:
# api/v1/users.py
from fastapi import APIRouter, Depends
from ...services.user_service import UserServicerouter = APIRouter()@router.post("/", response_model=UserResponse)
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_title="My App", layout="wide")# 路由邏輯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'] = f'Bearer {self.token}'async with httpx.AsyncClient() as client:response = await client.request(method, f"{self.base_url}{endpoint}", headers=headers, **kwargs)return response.json()
關鍵配置文件
1. docker-compose.yml
version: '3.8'
services:backend:build: ./backendports:- "8000:8000"environment:- DATABASE_URL=postgresql://user:pass@db:5432/myapp- REDIS_URL=redis://redis:6379depends_on:- db- redisfrontend:build: ./frontendports:- "8501:8501"environment:- API_BASE_URL=http://backend:8000depends_on:- backenddb:image: postgres:13environment:- POSTGRES_DB=myapp- POSTGRES_USER=user- POSTGRES_PASSWORD=passvolumes:- postgres_data:/var/lib/postgresql/dataredis:image: redis:7-alpineports:- "6379:6379"volumes: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.port=8501", "--server.address=0.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.txt
2. 開發模式啟動
# 啟動后端
cd backend
uvicorn app.main:app --reload --port 8000# 啟動前端(新終端)
cd frontend
streamlit run app.py --server.port 8501
3. 生產環境部署
# 使用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. 性能優化
- 數據庫查詢優化
- 緩存策略
- 異步處理
- 資源壓縮