全书目录

后端市政区

第八章:Python 后端 —— 数据和业务处理园区

2 分钟 598 字 第 8 / 962 个阅读单元

这一章里,把 Python 后端看成“数据处理园区”。有的楼偏 API,有的楼偏完整政务,有的楼专门拉物流车队跑后台任务。

Python 后端的主流不是“谁都和 Django 一个路子”,而是分成几种完全不同的城市治理方式。

#FastAPI —— 新式 API 快速通道

py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"hello": "world"}

FastAPI 的核心是:

  • 类型标注
  • 自动校验
  • 自动 OpenAPI 文档
  • ASGI / async 友好

适合:

  • 新 API
  • AI 应用后端
  • 数据服务
  • Python 团队的现代 Web 服务

#Django —— 老牌综合政务系统

py
from django.http import JsonResponse

def hello(request):
    return JsonResponse({"hello": "world"})

Django 的强项是:

  • ORM
  • Admin
  • Auth
  • 模板
  • 电池齐全

适合:

  • 后台系统
  • 业务系统
  • CMS
  • 需要成熟全家桶的项目

#Flask —— 轻量办事窗口

py
from flask import Flask

app = Flask(__name__)

@app.get("/")
def hello():
    return {"hello": "world"}

Flask 更像:

  • 小而轻
  • 容易理解
  • 你自己拼扩展

#Litestar —— 新派类型化 ASGI 市政厅

py
from litestar import Litestar, get

@get("/")
async def hello() -> dict[str, str]:
    return {"hello": "world"}

app = Litestar(route_handlers=[hello])

Litestar 面向的是:

  • 现代 ASGI
  • 类型安全
  • 高性能 API

#Celery —— 城市物流车队

py
from celery import Celery

app = Celery("tasks", broker="redis://localhost:6379/0")

@app.task
def send_email():
    return "sent"

Celery 不是 Web 框架。

它解决的是:

  • 异步任务
  • 后台作业
  • 定时任务
  • 队列消费

Python 后端速查

技术 更适合
FastAPI 现代 API、AI 服务、异步接口
Django 完整业务系统
Flask 小服务、教学、轻应用
Litestar 现代类型化 ASGI 团队
Celery 异步任务系统