Posted on:
Last modified:
FastAPI 中的 router 相当于 Flask 中的 Blueprint, 用来切分应用到不同的模块。
# views/users.py
from fastapi import APIRouter
router = APIRouter()
@router.get("/me")
def myinfo():
...
# main.py
from fastapi import FastAPI
from views import users
app = FastAPI()
app.include_router(users.router, prefix="/users")
模块化之后,自然需要考虑文件是怎么组织的。一般情况下,我会这么做:
|-- app.py
|-- views/
| |-- __init__.py
| |-- users.py
| |-- tasks.py
|-- depends/
| |-- __init__.py
| |-- db.py
| |-- users.py
|-- sql/
| |-- __init__.py
| |-- users.py
+-- schemas/
|-- __init__.py
|-- users.py
其中 app.py 存放 app实例,views 存放对应的 routers 文件,sql 存放 sqlalchemy 模型文件, schemas 存放对应的 pydantic 类型文件,depends 存放一些依赖文件,后面的章节会讲到。
一些文件的代码如下:
app.py
from fastapi import FastAPI
from views import users, tasks, ...
app = FastAPI()
app.include_router(users.router, prefix="/users", tags=["User"])
app.include_router(tasks.router, prefix="/tasks", tags=["Task"])
views/users.py
from fastapi import APIRouter
from pydantic import BaseModel
from schemas import UserModel
router = APIRouter()
class UserListOut(BaseModel):
users: list[UserModel]
@router.get("", response_model=UserListOut)
def list_users():
...
@router.get("/{user_id}", response_model=UserModel)
def get_user(user_id: int):
...
sql/users.py
from sqlalchemy import Boolean, Text, String, Column
from sqlalchemy.orm import declarative_base
Base = declarative_base()
class UserTable(Base):
__tablename__ = "users"
# 如果不是 sqlite,请使用 BIGINT
id = Column(Integer, autoincrement=True, primary_key=True)
...
schemas/users.py
from pydantic import BaseModel
class UserModel(BaseModel):
id: int
...
class Config:
orm_mode = True
depends/db.py
def dep_db():
db: Session = SessionLocal()
try:
yield db
except Exception:
db.rollback()
raise
finally:
db.close()
© 2016-2022 Yifei Kong. Powered by ynotes
All contents are under the CC-BY-NC-SA license, if not otherwise specified.
Opinions expressed here are solely my own and do not express the views or opinions of my employer.
友情链接: MySQL 教程站