首先是总的文件结构:.
├── __pycache__
│ └── main.cPython-38.pyc
├── main.py
└── sqlstu
├── __pycache__
│ ├── crud.cpython-38.pyc
│ ├── database.cpython-38.pyc
│ └── models.cpython-38.pyc
├── crud.py
├── database.py
└── models.py
main.py就是FastAPI的启动文件了。
main.py:import uvicorn
from pydantic import BaseModel
from sqlstu import crud
from sqlalchemy.orm import Session
from fastapi import Response, Depends, FastAPI, HTTPException
from sqlstu.database import SessionLocal, engine
from sqlstu import models
app = FastAPI()
models.Base.metadata.create_all(bind=engine)
# 数据库开关
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
class Item(BaseModel):
form: str