FastAPI-MySQL-Cookie程式碼實現

Melnis8發表於2024-04-13

連線資料庫

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from urllib.parse import quote_plus

password = '123456'
encoded_password = quote_plus(password)
SQLALCHEMY_DATABASE_URL = f'mysql+pymysql://root:{encoded_password}@127.0.0.1:3306/cookie_logging'


engine = create_engine(
    SQLALCHEMY_DATABASE_URL, echo=True
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

建模

from sqlalchemy import Boolean, Column, ForeignKey, Integer, String

from .database import Base

class Users(Base):
    __tablename__ = 'user'
    username = Column(String)
    id = Column(Integer, primary_key=True)
    password = Column(String)

介面

from typing import Annotated
import uvicorn
from fastapi import Cookie, FastAPI,Depends
from database import get_db
from fastapi.encoders import jsonable_encoder
from sqlalchemy.orm import Session
from logging_test import alchemy_models

app = FastAPI()


@app.get("/logging/")
async def read_items(id: Annotated[int | None, Cookie()], db: Session = Depends(get_db),):
    response = db.query(alchemy_models.Users).filter(alchemy_models.Users.id == id).first()
    if response:
        return jsonable_encoder(response)
    else:
        return jsonable_encoder({'error': f'{id} not found'})

tips

swagger文件傳送cookie會有異常,可以使用postman進行測試

相關文章