11.6 服务层与仓库模式
FastAPI入门教程:轻松学习Python Web开发与服务层仓库模式
本教程面向Python初学者,无Web开发经验,详细讲解FastAPI基础,通过动手实践和生活化类比,快速上手并理解服务层与仓库模式,建立Web开发信心。
FastAPI入门教程:从零开始学习Web开发
欢迎来到FastAPI入门教程!如果你是Python初学者,想尝试Web开发但不知从何下手,这里就是你的起点。本教程将一步步带你构建你的第一个API,并用简单的生活类比解释复杂概念,让你在动手实践中建立信心。
1. 什么是FastAPI?
FastAPI是一个现代、快速(高性能)的Python Web框架,专门用于构建API。它基于Python 3.6+的类型提示,自动生成文档,非常易于学习和使用。想象一下,FastAPI就像你的私人厨师,你告诉它想吃什么(你的请求),它就能快速准备出美味佳肴(响应)。
成功时刻:在几分钟内,你就能运行你的第一个API,看到结果!
2. 环境设置
首先,确保你有Python 3.6或更高版本。然后,安装FastAPI和Uvicorn(一个ASGI服务器,用来运行FastAPI应用)。
打开终端或命令提示符,运行以下命令:
pip install fastapi uvicorn
这就像组装你的工具箱,准备好建造东西!
3. 创建你的第一个API
让我们从一个简单的Hello World开始。创建一个新文件,命名为 main.py,并输入以下代码:
from fastapi import FastAPI
app = FastAPI() # 创建一个FastAPI应用实例,就像给餐厅起个名字
@app.get("/") # 定义一个GET请求路径,像在菜单上写一个菜名
async def read_root():
return {"message": "Hello, World!"} # 返回一个JSON响应,像厨师端出一盘菜
保存文件,然后在终端运行:
uvicorn main:app --reload
打开浏览器,访问 http://127.0.0.1:8000。看到 {"message": "Hello, World!"} 了吗?恭喜你!你刚刚创建了你的第一个Web API。这就是你的第一个“成功时刻”!
4. 添加路径参数和查询参数
让API更互动一点。路径参数就像指定菜品的具体选项,查询参数像额外要求。
更新 main.py:
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}") # 使用路径参数 {item_id}
async def read_item(item_id: int, q: str = None): # item_id是路径参数,q是可选查询参数
return {"item_id": item_id, "query": q}
访问 http://127.0.0.1:8000/items/5?q=test,你会看到返回JSON。试试不同值,体验参数如何工作!
5. 使用Pydantic模型处理数据
Pydantic模型帮助验证和结构化数据。想象一下,你要点餐,需要一个菜单表来确保你点的是正确的东西。
在 main.py 中添加:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel): # 定义一个数据模型,像菜单上的菜品描述
name: str
price: float
is_offer: bool = False
@app.post("/items/")
async def create_item(item: Item): # FastAPI会自动验证输入数据
return item
使用工具如Postman或curl发送POST请求到 http://127.0.0.1:8000/items/,body为JSON如 {"name": "Book", "price": 10.5, "is_offer": true}。看到数据被正确处理了吗?
6. 引入数据库和仓库模式
现在,让我们把数据存储起来。我们将使用SQLite数据库,并解释仓库模式。
首先,安装SQLAlchemy和数据库驱动:
pip install sqlalchemy databases[aiosqlite]
仓库模式:想象你有一个图书馆。仓库模式就像图书管理员,负责借书和还书(数据存取),而其他部分(如服务层)不需要知道书架怎么放书。这帮助分离关注点,使代码更清晰。
创建一个新文件 database.py:
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
DATABASE_URL = "sqlite:///./test.db" # SQLite数据库文件
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
class ItemDB(Base): # 定义数据库表,像图书馆的图书目录
__tablename__ = "items"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, index=True)
price = Column(Integer)
Base.metadata.create_all(bind=engine) # 创建表
7. 服务层:业务逻辑处理
服务层:现在,想象你是餐厅的经理。服务层就像服务员,负责处理顾客点餐(业务逻辑),然后告诉厨师(仓库模式)准备食物。它不直接操作厨房,只协调任务。
在 main.py 中,添加服务层和仓库模式的示例。首先,创建仓库函数来操作数据。
更新 main.py:
from fastapi import FastAPI, Depends
from sqlalchemy.orm import Session
from database import SessionLocal, ItemDB
from pydantic import BaseModel
from typing import List
app = FastAPI()
# 依赖项,获取数据库会话
async def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
# Pydantic模型
class Item(BaseModel):
name: str
price: float
class ItemResponse(BaseModel):
id: int
name: str
price: float
# 仓库模式函数
async def create_item_in_db(item: Item, db: Session):
db_item = ItemDB(name=item.name, price=item.price) # 创建数据库对象
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
async def get_items_from_db(db: Session):
return db.query(ItemDB).all()
# 服务层函数
async def item_service_create(item: Item, db: Session):
# 这里可以添加业务逻辑,如验证价格不能为负
if item.price < 0:
raise ValueError("Price cannot be negative")
return await create_item_in_db(item, db) # 调用仓库函数
async def item_service_get_all(db: Session):
return await get_items_from_db(db)
# API端点,使用服务层
@app.post("/items/", response_model=ItemResponse)
async def create_item(item: Item, db: Session = Depends(get_db)):
db_item = await item_service_create(item, db) # 通过服务层处理
return db_item
@app.get("/items/", response_model=List[ItemResponse])
async def read_items(db: Session = Depends(get_db)):
items = await item_service_get_all(db)
return items
运行应用并测试端点。现在,你有了一个完整的CRUD API,使用了服务层和仓库模式!访问 http://127.0.0.1:8000/docs 查看自动生成的交互式文档,这是一个巨大的“成功时刻”——你可以直接在浏览器中测试API。
8. 总结和下一步
你已经学会了FastAPI的基础:
- 安装和运行第一个API。
- 使用路径参数、查询参数和Pydantic模型。
- 集成数据库,并引入仓库模式来管理数据存取。
- 使用服务层处理业务逻辑,使代码模块化。
生活化类比回顾:
- FastAPI:像你的私人厨师,快速响应请求。
- 仓库模式:像图书馆管理员,专注数据存储。
- 服务层:像餐厅服务员,协调业务逻辑。
继续探索FastAPI的更多功能,如认证、中间件和异步支持。动手实践是关键——尝试构建你自己的小项目,比如待办事项列表API。
希望这个教程帮助你建立了Web开发的信心!记住,每次运行代码看到结果,都是一个胜利。加油!