FastAPI-MySQL-Cookie代码实现

连接数据库

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进行测试

posted @   Melnis8  阅读(17)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示