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 pydantic[dotenv]

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=List[UserResponse])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

相关推荐
ZhengEnCi1 天前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风1 天前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python
明月_清风1 天前
Python 消失的内存:为什么 list=[] 是新手最容易踩的“毒苹果”?
后端·python
Flittly2 天前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(3)TodoWrite (待办写入)
python·agent
千寻girling2 天前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook2 天前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风2 天前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风2 天前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python
helloweilei3 天前
python 抽象基类
python
用户8356290780513 天前
Python 实现 PPT 转 HTML
后端·python