imetting_backend/app/api/endpoints/users.py

56 lines
2.1 KiB
Python

from fastapi import APIRouter, HTTPException, Depends
from app.models.models import UserInfo
from app.core.database import get_db_connection
from app.core.auth import get_current_user
router = APIRouter()
@router.get("/users", response_model=list[UserInfo])
def get_all_users(current_user: dict = Depends(get_current_user)):
with get_db_connection() as connection:
cursor = connection.cursor(dictionary=True)
query = '''
SELECT
user_id, username, caption, email, created_at,
(SELECT COUNT(*) FROM meetings WHERE user_id = u.user_id) as meetings_created,
(SELECT COUNT(*) FROM attendees WHERE user_id = u.user_id) as meetings_attended
FROM users u
ORDER BY caption ASC
'''
cursor.execute(query)
users = cursor.fetchall()
return [UserInfo(**user) for user in users]
@router.get("/users/{user_id}", response_model=UserInfo)
def get_user_info(user_id: int, current_user: dict = Depends(get_current_user)):
with get_db_connection() as connection:
cursor = connection.cursor(dictionary=True)
user_query = "SELECT user_id, username, caption, email, created_at FROM users WHERE user_id = %s"
cursor.execute(user_query, (user_id,))
user = cursor.fetchone()
if not user:
raise HTTPException(status_code=404, detail="用户不存在")
created_query = "SELECT COUNT(*) as count FROM meetings WHERE user_id = %s"
cursor.execute(created_query, (user_id,))
meetings_created = cursor.fetchone()['count']
attended_query = "SELECT COUNT(*) as count FROM attendees WHERE user_id = %s"
cursor.execute(attended_query, (user_id,))
meetings_attended = cursor.fetchone()['count']
return UserInfo(
user_id=user['user_id'],
username=user['username'],
caption=user['caption'],
email=user['email'],
created_at=user['created_at'],
meetings_created=meetings_created,
meetings_attended=meetings_attended
)