Python的后端框架

Python的后端框架

一.Django

1.类型

全栈重型框架

2.核心特性

内置 ORM、Admin 后台、认证、表单、缓存等;MTV 架构

3.适用场景

企业级应用、CMS、电商平台、数据后台

4.性能

~2,000 RPS

二、Flask

1.类型

轻量微框架

2.核心特性

极简核心,高度可扩展;通过插件(如 Flask-SQLAlchemy)按需添加功能;灵活自由

3.适用场景

微服务、小型 API、原型开发、小型项目

4.性能

~3,000 RPS

三、FastAPI

1.类型

现代异步框架

2.核心特性

原生支持 async/await ;自动 OpenAPI/ Swagger文档;基于Pydantic类型校验,高性能(接近Nodejs)

3.适用场景
复制代码
高并发 API、实时服务、机器学习模型部署	
4.性能
复制代码
~12,500 RPS

代码:

安装依赖

pip install fastapi uvicorn sqlalchemy pydanticdotenv

main.py

from fastapi import FastAPI, HTTPExceptionfrom pydantic import BaseModelfrom sqlalchemy import create_engine, Column, Integer, Stringfrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy.orm import sessionmakerfrom typing import List# === 1. 创建数据库(SQLite 示例)DATABASE_URL = "sqlite:///./users.db"engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)Base = declarative_base()# === 2. 定义数据库模型class UserTable(Base): tablename = "users" id = Column(Integer, primary_key=True, index=True) name = Column(String(50), nullable=False) email = Column(String(100), unique=True, index=True)# 创建表Base.metadata.create_all(bind=engine)# === 3. Pydantic 模型(用于 API 输入输出校验)class UserCreate(BaseModel): name: str email: strclass UserResponse(UserCreate): id: int class Config: from_attributes = True # 兼容 SQLAlchemy 对象# === 4. 创建 FastAPI 应用app = FastAPI( title="✨ 用户管理系统", description="一个超简单的 FastAPI 后端示例", version="0.1.0")# === 5. CRUD 接口@app.post("/users", response_model=UserResponse, status_code=201)def create_user(user: UserCreate): db = SessionLocal() db_user = UserTable(**user.model_dump()) try: db.add(db_user) db.commit() db.refresh(db_user) return db_user except Exception: raise HTTPException(status_code=400, detail="邮箱已存在") finally: db.close()@app.get("/users", response_model=ListUserResponse)def read_users(): db = SessionLocal() users = db.query(UserTable).all() db.close() return users@app.get("/users/{user_id}", response_model=UserResponse)def read_user(user_id: int): db = SessionLocal() user = db.query(UserTable).filter(UserTable.id == user_id).first() db.close() if not user: raise HTTPException(status_code=404, detail="用户不存在") return user@app.put("/users/{user_id}", response_model=UserResponse)def update_user(user_id: int, user: UserCreate): db = SessionLocal() db_user = db.query(UserTable).filter(UserTable.id == user_id).first() if not db_user: raise HTTPException(status_code=404, detail="用户不存在") db_user.name = user.name db_user.email = user.email db.commit() db.refresh(db_user) db.close() return db_user@app.delete("/users/{user_id}", status_code=204)def delete_user(user_id: int): db = SessionLocal() db_user = db.query(UserTable).filter(UserTable.id == user_id).first() if not db_user: raise HTTPException(status_code=404, detail="用户不存在") db.delete(db_user) db.commit() db.close() return None

运行如下代码:

uvicorn main:app --reload

打印如下输出:

Uvicorn running on http://127.0.0.1:8000

相关推荐
兵慌码乱8 小时前
基于 MediaPipe 与 PySide2 的手势交互音乐控制系统实现:轻量化视觉交互全流程解析
python·opencv·计算机视觉·人机交互·手势识别·mediapipe·pyside2
luckdewei10 小时前
FastAPI 资产管理系统实战:复杂 ORM 关联、Alembic 迁移与 N+1 查询优化
python
aqi0016 小时前
15天学会AI应用开发(八)使用向量数据库实现RAG功能
人工智能·python·大模型·ai编程·ai应用
Csvn17 小时前
`functools.lru_cache` —— 一行代码搞定缓存加速
后端·python
金銀銅鐵1 天前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup112 天前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi002 天前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵2 天前
用 Python 实现 Take-Away 游戏
python·游戏