main
HuangHai 4 months ago
parent f54cdd47cf
commit 5147d767b2

@ -149,37 +149,40 @@ async def get_docx_stream(
async def generate_stream(): async def generate_stream():
summary = "" summary = ""
try: try:
async for chunk in response: # 使用 async for 处理流式响应 # 获取数据库连接
if chunk.choices[0].delta.content: # 检查是否有内容 db = await app.state.pool.acquire()
async for chunk in response:
if chunk.choices[0].delta.content:
chunk_content = chunk.choices[0].delta.content chunk_content = chunk.choices[0].delta.content
# 逐字拆分并返回
for char in chunk_content: for char in chunk_content:
# print(char, end="", flush=True) # 逐字输出到控制台 print(char, end="", flush=True)
yield char.encode("utf-8") # 将字符编码为 UTF-8 字节 yield char.encode("utf-8")
summary += char # 将内容拼接到 summary 中 summary += char
# 流式传输完成后,生成 Word 文档 # 流式传输完成后,生成 Word 文档
markdown_to_docx(summary, output_file=filename) markdown_to_docx(summary, output_file=filename)
# 记录到数据库 # 记录到数据库
await update_question_by_id(db, question_id, docx_file_name=filename) await update_question_by_id(db, question_id, docx_file_name=filename)
#await db.execute("UPDATE t_bi_question SET docx_file_name = $1 WHERE id = $2", filename, question_id)
except asyncio.CancelledError: except asyncio.CancelledError:
# 客户端提前断开连接,无需处理 # 客户端提前断开连接,无需处理
print("客户端断开连接") print("客户端断开连接")
except Exception as e: except Exception as e:
# 如果发生异常,返回错误信息
error_response = json.dumps({ error_response = json.dumps({
"success": False, "success": False,
"message": f"生成Word文件失败: {str(e)}" "message": f"生成Word文件失败: {str(e)}"
}) })
# print(error_response) # 输出错误信息到控制台 print(error_response)
yield error_response.encode("utf-8") # 将错误信息编码为 UTF-8 字节 yield error_response.encode("utf-8")
finally: finally:
# 确保资源释放 # 确保资源释放
if "response" in locals(): if "response" in locals():
await response.close() await response.close()
if "db" in locals():
await app.state.pool.release(db) # 释放连接回连接池
# 使用 StreamingResponse 返回流式结果 # 使用 StreamingResponse 返回流式结果
return StreamingResponse( return StreamingResponse(

Loading…
Cancel
Save