FastAPI: APIRouter(17)

从前面的例子看,所有的Views操作都放在一个文件里,代码不易维护。为了更好的管理路径和代码,可以通过APIRouter来为该模块创建路径操作,给我们提供了在多个文件中注册路由的功能。

使用Router

在项目下创建routers -> users.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from models import crud,schemas
from dependencies import get_db

router = APIRouter()


# 新建用户
@router.post("/users/", response_model=schemas.User, tags=['users'])
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
return crud.create_user(db, user=user)


# 通过id查询用户
@router.get("/user/{user_id}", response_model=schemas.User, tags=['users'])
def read_user(user_id: int, db: Session = Depends(get_db)):
db_user = crud.get_user(db, user_id=user_id)
if not db_user:
raise HTTPException(status_code=404, detail="User not found")
return db_user


# 所有用户
@router.get('/users/', response_model=List[schemas.User], tags=['users'])
def read_users(start: int=0, limit: int=10, db: Session = Depends(get_db)):
return crud.get_users(db, start, limit)

# Delete user
@router.delete('/user/{user_id}', response_model=schemas.User, tags=['users'])
def delete_user(user_id: int, db: Session = Depends(get_db)):
db_user = crud.delete_user(db, user_id=user_id)
if not db_user:
raise HTTPException(status_code=400, detail='User not found')
return db_user

# Update User
@router.put('/user/{user_id}', response_model=schemas.User, tags=['users'])
def update_user(user_id: int, update_user: schemas.UserUpdate, db: Session = Depends(get_db)):
db_user = crud.update_user(db, user_id=user_id, update_user=update_user)
if not db_user:
raise HTTPException(status_code=400, detail='User not found')
return db_user

注册Router

将我们的 APIRouter 注册到核心对象上去。main.py

1
2
3
4
5
6
7
8
9
10
# 导入 FastAPI
from fastapi import FastAPI
from routers import users
import uvicorn
import config

# 实例化 FastAPI
app = FastAPI()

app.include_router(users.router)

唐胡璐 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
分享创造价值,您的支持将鼓励我继续前行!