Files
diary-news/backend/app/api/subscriptions.py
Mavis 5109d6f824 fix: API 全部改用显式两步走 await session.execute + result.scalars()
之前 (await ...).scalars() 链式在 SQLAlchemy 2.0 async 下报
'coroutine' has no attribute 'scalars' 错误。改为先 await 拿 result
再 .scalars(),这是 SQLAlchemy 2.0 推荐的 async 写法。
2026-06-07 23:22:56 +08:00

68 lines
2.0 KiB
Python

"""/subscriptions 关键词订阅。"""
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.deps import get_current_user
from app.database import get_session
from app.models.subscription import Subscription
from app.models.user import User
from app.schemas.misc import SubscriptionIn, SubscriptionOut
router = APIRouter(prefix="/subscriptions", tags=["subscriptions"])
@router.post("", response_model=SubscriptionOut, status_code=status.HTTP_201_CREATED)
async def create(
body: SubscriptionIn,
user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session),
):
sub = Subscription(
user_id=user.id,
keyword=body.keyword,
match_in=body.match_in,
channel=body.channel,
target=body.target,
)
session.add(sub)
await session.commit()
await session.refresh(sub)
return SubscriptionOut.model_validate(sub)
@router.get("", response_model=list[SubscriptionOut])
async def list_mine(
user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session),
):
result = await session.execute(
select(Subscription)
.where(Subscription.user_id == user.id)
.order_by(Subscription.created_at.desc())
)
rows = result.scalars()
return [SubscriptionOut.model_validate(s) for s in rows]
@router.delete("/{sub_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete(
sub_id: int,
user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session),
):
sub = (
await session.execute(
select(Subscription).where(
Subscription.id == sub_id, Subscription.user_id == user.id
)
)
).scalar_one_or_none()
if not sub:
raise HTTPException(status.HTTP_404_NOT_FOUND, "Subscription not found")
await session.delete(sub)
await session.commit()
return None