重构代码
This commit is contained in:
70
router/mp_router.py
Normal file
70
router/mp_router.py
Normal file
@@ -0,0 +1,70 @@
|
||||
"""
|
||||
Author: Yutang LI
|
||||
Institution: SIAT-MIC
|
||||
Contact: yt.li2@siat.ac.cn
|
||||
"""
|
||||
|
||||
import os
|
||||
from fastapi import APIRouter, Request
|
||||
import json
|
||||
import logging
|
||||
import datetime
|
||||
from typing import Dict
|
||||
from services.mp_service import (
|
||||
parse_search_parameters,
|
||||
process_search_results,
|
||||
execute_search
|
||||
)
|
||||
from utils import handle_minio_upload
|
||||
from error_handlers import handle_general_error
|
||||
|
||||
router = APIRouter(prefix="/mp", tags=["Material Project"])
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@router.get("/search")
|
||||
async def search_from_material_project(request: Request):
|
||||
# 打印请求日志
|
||||
logger.info(f"Received request: {request.method} {request.url}")
|
||||
logger.info(f"Query parameters: {request.query_params}")
|
||||
|
||||
try:
|
||||
# 解析查询参数
|
||||
search_args = parse_search_parameters(request.query_params)
|
||||
|
||||
# 执行搜索
|
||||
docs = await execute_search(search_args)
|
||||
|
||||
# 处理搜索结果
|
||||
res = process_search_results(docs)
|
||||
|
||||
if len(res) == 0:
|
||||
return {"status": "success", "data": "No results found, please try again."}
|
||||
|
||||
# 上传结果到MinIO
|
||||
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
|
||||
file_name = f"mp_search_results_{timestamp}.json"
|
||||
|
||||
# 将结果写入临时文件
|
||||
with open(file_name, 'w') as f:
|
||||
json.dump(res, f, indent=2)
|
||||
|
||||
# 上传并获取URL
|
||||
url = handle_minio_upload(file_name, file_name)
|
||||
|
||||
# 删除临时文件
|
||||
os.remove(file_name)
|
||||
|
||||
# 格式化返回结果
|
||||
res_chunk = "```json\n" + json.dumps(res[:5], indent=2) + "\n```"
|
||||
res_template = f"""
|
||||
好的,以下是用户的查询结果:
|
||||
由于返回长度的限制,我们只能返回前5个结果。如下:
|
||||
{res_chunk}
|
||||
如果用户需要更多的结果,请提示用户修改查询条件,或者尝试使用其他查询参数。
|
||||
同时我们将全部的的查询结果上传到MinIO中,请你提示用户可以通过以下链接下载:
|
||||
[Download]({url})
|
||||
"""
|
||||
return {"status": "success", "data": res_template}
|
||||
|
||||
except Exception as e:
|
||||
return handle_general_error(e)
|
||||
Reference in New Issue
Block a user