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

相关推荐
weixin_440730501 小时前
函数return、参数、参数组、递归函数、高阶函数等小结
开发语言·python
天赐范式1 小时前
天赐范式第181天:让视图开始切换——PBFT视图切换与从safety到liveness的跨越
python·pbft·数字生命·天赐范式·动态运行时·拜占庭容错
sugarzhangnotes2 小时前
【无标题】
开发语言·人工智能·python
weixin_447195292 小时前
【无标题】
pytorch·python
迅猛龙办公室2 小时前
Python实现简单的人名对话
python
阿坨3 小时前
firestart:一行命令启动你的日常应用和网页
python·pypi·cli·click
老歌老听老掉牙3 小时前
麻花钻切屑形态演变的力学机制与临界条件分析
python·算法·钻头
happylifetree4 小时前
Python18(补充):练习
python
weixin_416667964 小时前
银河麒麟V10看门狗试验-1
网络·chrome·python
古城小栈4 小时前
Pydantic 从入门到实践全讲解
python