refactor(database): migrate to sqlmodel
This commit is contained in:
@@ -1,7 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlmodel import Session, create_engine
|
||||
|
||||
try:
|
||||
import redis
|
||||
@@ -11,7 +10,6 @@ from app.config import settings
|
||||
|
||||
# 数据库引擎
|
||||
engine = create_engine(settings.DATABASE_URL)
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
# Redis 连接
|
||||
if redis:
|
||||
@@ -22,11 +20,8 @@ else:
|
||||
|
||||
# 数据库依赖
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
with Session(engine) as session:
|
||||
yield session
|
||||
|
||||
|
||||
# Redis 依赖
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
from fastapi import Depends, HTTPException
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from sqlalchemy.orm import Session
|
||||
from __future__ import annotations
|
||||
|
||||
from app.auth import get_token_by_access_token
|
||||
|
||||
from .database import get_db
|
||||
from app.database import (
|
||||
User as DBUser,
|
||||
)
|
||||
|
||||
from .database import get_db
|
||||
|
||||
from fastapi import Depends, HTTPException
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from sqlmodel import Session, select
|
||||
|
||||
security = HTTPBearer()
|
||||
|
||||
|
||||
@@ -29,5 +31,5 @@ async def get_current_user_by_token(token: str, db: Session) -> DBUser | None:
|
||||
token_record = get_token_by_access_token(db, token)
|
||||
if not token_record:
|
||||
return None
|
||||
user = db.query(DBUser).filter(DBUser.id == token_record.user_id).first()
|
||||
user = db.exec(select(DBUser).where(DBUser.id == token_record.user_id)).first()
|
||||
return user
|
||||
|
||||
Reference in New Issue
Block a user