59 lines
1.9 KiB
Python
59 lines
1.9 KiB
Python
"""
|
|
Author: Yutang LI
|
|
Institution: SIAT-MIC
|
|
Contact: yt.li2@siat.ac.cn
|
|
"""
|
|
import os
|
|
from fastapi import APIRouter, Request
|
|
from fastapi.responses import JSONResponse
|
|
import logging
|
|
from error_handlers import handle_general_error
|
|
from services.oqmd_service import (
|
|
fetch_oqmd_data,
|
|
parse_oqmd_html,
|
|
render_and_save_charts
|
|
)
|
|
|
|
router = APIRouter(prefix="/oqmd", tags=["OQMD"])
|
|
logger = logging.getLogger(__name__)
|
|
|
|
@router.get("/search")
|
|
async def search_from_oqmd_by_composition(request: Request):
|
|
"""通过成分搜索OQMD数据"""
|
|
try:
|
|
# 打印请求日志
|
|
logger.info(f"Received request: {request.method} {request.url}")
|
|
logger.info(f"Query parameters: {request.query_params}")
|
|
|
|
# 获取并解析数据
|
|
composition = request.query_params['composition']
|
|
html = await fetch_oqmd_data(composition)
|
|
basic_data, table_data, phase_data = parse_oqmd_html(html)
|
|
|
|
# 渲染并保存图表
|
|
phase_diagram_url = await render_and_save_charts(phase_data)
|
|
|
|
# 返回格式化后的响应
|
|
return JSONResponse(
|
|
status_code=200,
|
|
content={
|
|
"status": "success",
|
|
"data": format_response(basic_data, table_data, phase_diagram_url)
|
|
}
|
|
)
|
|
|
|
except Exception as e:
|
|
return handle_general_error(e)
|
|
|
|
def format_response(basic_data: list, table_data: str, phase_data: str) -> str:
|
|
"""格式化响应数据"""
|
|
response = "### OQMD Data\n"
|
|
for item in basic_data:
|
|
response += f"**{item}**\n"
|
|
response += "\n### Phase Diagram\n\n"
|
|
response += f"\n\n"
|
|
response += "\n### Compounds at this composition\n\n"
|
|
response += "I highly recommend that you pass the phase map URL to the user wrapped in Markdown's image syntax!"
|
|
response += f"{table_data}\n"
|
|
return response
|