FastApi使用
1、环境变量配置
pip install fastapi
pip install databases
pip install pymysql
pip install aiomysql
pip install pydantic
db 导入依赖
import pymysql
pymysql.install_as_MySQLdb()
2、项目结构
.
│ main.py
│
├─app
│ │ db.py
│ │
│ ├─api
│ │ │ crud.py
│ │ │ models.py
│ │ │ notes.py
3、启动命令
uvicorn main:app --reload
4、项目搭建
4.1、配置db.py
import pymysql
from sqlalchemy import Column,DateTime, Integer,MetaData,String,Table,create_engine
from sqlalchemy.sql import func
from databases import Database
pymysql.install_as_MySQLdb()
# DATABASE_URL = os.getenv("DATABASE_URL")
DATABASE_URL = "mysql://root:JBWewwZ041XPLtxM@localhost:3306/book"
# databases query builder
database = Database(DATABASE_URL)
# SQLAlchemy
engine = create_engine(DATABASE_URL)
metadata = MetaData()
notes = Table(
"notes",
metadata,
Column("id", Integer, primary_key=True),
Column("title", String(50)),
Column("description", String(50)),
Column("created_date", DateTime, default=func.now(), nullable=False),
)
4.2、配置models.py
from pydantic import BaseModel, Field
class NoteSchema(BaseModel):
title: str = Field(..., min_length=3, max_length=50)
description: str = Field(..., min_length=3, max_length=50)
class NoteDB(NoteSchema):
id: int
4.3、配置crud.py
from app.api.models import NoteSchema
from app.db import notes, database
async def post(payload: NoteSchema):
query = notes.insert().values(title=payload.title, description=payload.description)
return await database.execute(query=query)
async def get(id: int):
query = notes.select().where(id == notes.c.id)
return await database.fetch_one(query=query)
async def get_all():
query = notes.select()
return await database.fetch_all(query=query)
async def put(id: int, payload: NoteSchema):
query = (
notes
.update()
.where(id == notes.c.id)
.values(title=payload.title, description=payload.description)
.returning(notes.c.id)
)
return await database.execute(query=query)
async def delete(id: int):
query = notes.delete().where(id == notes.c.id)
return await database.execute(query=query)
4.4、配置notes.py
from typing import List
from fastapi import APIRouter, HTTPException, Path
from app.api import crud
from app.api.models import NoteDB, NoteSchema
router = APIRouter()
@router.post("/", response_model=NoteDB, status_code=201)
async def create_note(payload: NoteSchema):
note_id = await crud.post(payload)
response_object = {
"id": note_id,
"title": payload.title,
"description": payload.description,
}
return response_object
@router.get("/{id}/", response_model=NoteDB)
async def read_note(id: int = Path(..., gt=0),):
note = await crud.get(id)
if not note:
raise HTTPException(status_code=404, detail="Note not found")
return note
@router.get("/", response_model=List[NoteDB])
async def read_all_notes():
return await crud.get_all()
@router.put("/{id}/", response_model=NoteDB)
async def update_note(payload: NoteSchema, id: int = Path(..., gt=0),):
note = await crud.get(id)
if not note:
raise HTTPException(status_code=404, detail="Note not found")
note_id = await crud.put(id, payload)
response_object = {
"id": note_id,
"title": payload.title,
"description": payload.description,
}
return response_object
@router.delete("/{id}/", response_model=NoteDB)
async def delete_note(id: int = Path(..., gt=0)):
note = await crud.get(id)
if not note:
raise HTTPException(status_code=404, detail="Note not found")
await crud.delete(id)
return note
4.5、配置main.py
from fastapi import FastAPI
from app.api import notes, ping
from app.db import database, engine, metadata
metadata.create_all(engine)
app = FastAPI()
@app.on_event("startup")
async def startup():
await database.connect()
@app.on_event("shutdown")
async def shutdown():
await database.disconnect()
app.include_router(ping.router)
app.include_router(notes.router, prefix="/notes", tags=["notes"])