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

相关推荐
小二·20 小时前
Python Web 开发进阶实战:性能压测与调优 —— Locust + Prometheus + Grafana 构建高并发可观测系统
前端·python·prometheus
七牛云行业应用21 小时前
重构实录:我删了 5 家大模型 SDK,只留了 OpenAI 标准库
python·系统架构·大模型·aigc·deepseek
知乎的哥廷根数学学派21 小时前
基于多模态特征融合和可解释性深度学习的工业压缩机异常分类与预测性维护智能诊断(Python)
网络·人工智能·pytorch·python·深度学习·机器学习·分类
一人の梅雨21 小时前
亚马逊SP-API商品详情接口轻量化实战:合规与商业价值提取指南
python
袁气满满~_~1 天前
Python数据分析学习
开发语言·笔记·python·学习
axinawang1 天前
二、信息系统与安全--考点--浙江省高中信息技术学考(Python)
python·浙江省高中信息技术
寻星探路1 天前
【算法专题】滑动窗口:从“无重复字符”到“字母异位词”的深度剖析
java·开发语言·c++·人工智能·python·算法·ai
Dxy12393102161 天前
python连接minio报错:‘SSL routines‘, ‘ssl3_get_record‘, ‘wrong version number‘
开发语言·python·ssl
吨吨不打野1 天前
CS336——2. PyTorch, resource accounting
人工智能·pytorch·python
___波子 Pro Max.1 天前
Python文件读取代码中strip()的作用
python