|
|
|
@ -43,13 +43,15 @@ async def truncate_chat_log(mysql_pool):
|
|
|
|
|
logger.info("表 t_chat_log 已清空。")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
from aiomysql import DictCursor
|
|
|
|
|
|
|
|
|
|
# 分页查询聊天记录
|
|
|
|
|
async def get_chat_log_by_session(mysql_pool, session_id, page=None, page_size=10):
|
|
|
|
|
async def get_chat_log_by_session(mysql_pool, session_id, page=1, page_size=10):
|
|
|
|
|
"""
|
|
|
|
|
根据 session_id 查询聊天记录,并按 id 升序分页
|
|
|
|
|
根据 session_id 查询聊天记录,并按 id 降序分页
|
|
|
|
|
:param mysql_pool: MySQL 连接池
|
|
|
|
|
:param session_id: 用户会话 ID
|
|
|
|
|
:param page: 当前页码(如果为 None,则默认跳转到最后一页)
|
|
|
|
|
:param page: 当前页码(默认值为 1,但会动态计算为最后一页)
|
|
|
|
|
:param page_size: 每页记录数
|
|
|
|
|
:return: 分页数据
|
|
|
|
|
"""
|
|
|
|
@ -57,42 +59,41 @@ async def get_chat_log_by_session(mysql_pool, session_id, page=None, page_size=1
|
|
|
|
|
raise ValueError("MySQL 连接池未初始化")
|
|
|
|
|
|
|
|
|
|
async with mysql_pool.acquire() as conn:
|
|
|
|
|
async with conn.cursor() as cur:
|
|
|
|
|
async with conn.cursor(DictCursor) as cur: # 使用 DictCursor
|
|
|
|
|
# 查询总记录数
|
|
|
|
|
await cur.execute(
|
|
|
|
|
"SELECT COUNT(*) FROM t_chat_log WHERE session_id = %s",
|
|
|
|
|
(session_id,)
|
|
|
|
|
)
|
|
|
|
|
total = (await cur.fetchone())[0]
|
|
|
|
|
total = (await cur.fetchone())['COUNT(*)']
|
|
|
|
|
|
|
|
|
|
# 计算总页数
|
|
|
|
|
total_pages = (total + page_size - 1) // page_size
|
|
|
|
|
|
|
|
|
|
# 如果未指定页码,则默认跳转到最后一页
|
|
|
|
|
if page is None:
|
|
|
|
|
page = total_pages
|
|
|
|
|
|
|
|
|
|
# 计算偏移量
|
|
|
|
|
offset = (page - 1) * page_size
|
|
|
|
|
|
|
|
|
|
# 查询分页数据,按 id 升序排列
|
|
|
|
|
# 查询分页数据,按 id 降序排列
|
|
|
|
|
await cur.execute(
|
|
|
|
|
"SELECT id, session_id, user_input, model_response, audio_url, duration, create_time "
|
|
|
|
|
"FROM t_chat_log WHERE session_id = %s ORDER BY id ASC LIMIT %s OFFSET %s",
|
|
|
|
|
"FROM t_chat_log WHERE session_id = %s ORDER BY id DESC LIMIT %s OFFSET %s",
|
|
|
|
|
(session_id, page_size, offset)
|
|
|
|
|
)
|
|
|
|
|
records = await cur.fetchall()
|
|
|
|
|
|
|
|
|
|
# 将查询结果反转,确保最新消息显示在最后
|
|
|
|
|
records.reverse()
|
|
|
|
|
|
|
|
|
|
# 将查询结果转换为字典列表
|
|
|
|
|
result = [
|
|
|
|
|
{
|
|
|
|
|
"id": record[0],
|
|
|
|
|
"session_id": record[1],
|
|
|
|
|
"user_input": record[2],
|
|
|
|
|
"model_response": record[3],
|
|
|
|
|
"audio_url": record[4],
|
|
|
|
|
"duration": record[5],
|
|
|
|
|
"create_time": record[6].strftime("%Y-%m-%d %H:%M:%S")
|
|
|
|
|
"id": record['id'],
|
|
|
|
|
"session_id": record['session_id'],
|
|
|
|
|
"user_input": record['user_input'],
|
|
|
|
|
"model_response": record['model_response'],
|
|
|
|
|
"audio_url": record['audio_url'],
|
|
|
|
|
"duration": record['duration'],
|
|
|
|
|
"create_time": record['create_time'].strftime("%Y-%m-%d %H:%M:%S")
|
|
|
|
|
}
|
|
|
|
|
for record in records
|
|
|
|
|
]
|
|
|
|
|