Files
d3i-szct/dock/govc/govc_scrape_detail.py
2026-06-02 17:46:38 +08:00

68 lines
2.9 KiB
Python

import asyncio
import json
import pandas as pd
from tornado.httpclient import HTTPResponse, HTTPRequest
from sqlalchemy import select
from dock.govc import govc_api
import models
from models.govc_task_detail import GovcTaskDetail
from models.govc_task_attachment import GovcTaskAttachment
from paste.util import udict
from paste.core.logging import echo_log
async def get_detail_request(cguid: str):
"""
获取市12345的工单的详情信息,请求响应是单条工单的数据
:param cguid: 工单列表请求返回的cguid
"""
api_url = '/rest/sztaskworkordercommonrest/getDetail'
headers = {
'Referer': f'{govc_api.ApiUrl}/rest/sztaskworkordercommonrest/getDetail'
}
request_body = {
'caseguid': cguid, 'secret': 1
}
# 构造 API 请求
return await govc_api.new_api_request(api_url, request_body, headers=headers, method='GET')
async def after_detail_request(response: HTTPResponse, retry_queue: asyncio.Queue[HTTPRequest]):
"""
任务请求响应后的处理程序。
:param response: 响应对象
:param retry_queue: 重试队列
"""
response_body = response.body.decode()
response_data = json.loads(response_body)
detail_info = udict.get_by_path(response_data, 'params')
if detail_info:
mapped_df = pd.DataFrame([detail_info])
# 更换映射方向,用于将源数据列名改为与数据库表对应
forward_mapping = {dict_f: table_f for table_f, dict_f in GovcTaskDetail.FieldMapping.items()}
mapped_df = mapped_df.rename(columns=forward_mapping)
# 这里把空数据都换成 None,以便存入数据库时是 null
mapped_df.replace(models.EmptyInDF + models.EmptyDatetimeInDF, None, inplace=True)
task_id = getattr(response.request, GovcTaskDetail.task_id.key)
mapped_df[GovcTaskDetail.task_id.key] = task_id
# 筛选数据状态
_created, _updated = await GovcTaskDetail.save_batch(mapped_df)
echo_log(f"成功创建详情信息:{_created}条,更新:{_updated}条.")
files = udict.get_by_path(detail_info, 'files')
if files:
attachment_df = pd.DataFrame(files)
attachment_df[GovcTaskAttachment.task_id.key] = task_id
detail_query = select(GovcTaskDetail.id).where(GovcTaskDetail.task_id == task_id)
detail_id = await GovcTaskDetail.query_first(detail_query)
attachment_df[GovcTaskAttachment.detail_id.key] = detail_id
_created, _updated = await GovcTaskAttachment.save_batch(attachment_df)
echo_log(f"成功创建附件信息:{_created}条,更新:{_updated}条.")
else:
echo_log('未获取到详情信息')
if retry_queue:
echo_log(f"详情信息重试队列中有:{retry_queue.qsize()} 个请求在等待.")