main
HuangHai 4 months ago
parent f54cdd47cf
commit 5147d767b2

@ -149,37 +149,40 @@ async def get_docx_stream(
async def generate_stream():
summary = ""
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
# 逐字拆分并返回
for char in chunk_content:
# print(char, end="", flush=True) # 逐字输出到控制台
yield char.encode("utf-8") # 将字符编码为 UTF-8 字节
summary += char # 将内容拼接到 summary 中
print(char, end="", flush=True)
yield char.encode("utf-8")
summary += char
# 流式传输完成后,生成 Word 文档
markdown_to_docx(summary, output_file=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:
# 客户端提前断开连接,无需处理
print("客户端断开连接")
except Exception as e:
# 如果发生异常,返回错误信息
error_response = json.dumps({
"success": False,
"message": f"生成Word文件失败: {str(e)}"
})
# print(error_response) # 输出错误信息到控制台
yield error_response.encode("utf-8") # 将错误信息编码为 UTF-8 字节
print(error_response)
yield error_response.encode("utf-8")
finally:
# 确保资源释放
if "response" in locals():
await response.close()
if "db" in locals():
await app.state.pool.release(db) # 释放连接回连接池
# 使用 StreamingResponse 返回流式结果
return StreamingResponse(

Loading…
Cancel
Save