Files
LangBot/pkg/audit/center/apigroup.py

89 lines
2.1 KiB
Python
Raw Normal View History

2024-01-30 16:13:33 +08:00
from __future__ import annotations
import abc
import uuid
import json
2023-12-21 17:03:58 +08:00
import logging
2024-01-29 21:58:47 +08:00
import asyncio
2024-01-29 21:58:47 +08:00
import aiohttp
2023-12-21 16:48:50 +08:00
import requests
2024-11-16 12:40:57 +08:00
from ...core import app, entities as core_entities
2024-01-29 21:58:47 +08:00
class APIGroup(metaclass=abc.ABCMeta):
"""API 组抽象类"""
_basic_info: dict = None
_runtime_info: dict = None
prefix = None
2024-01-29 21:58:47 +08:00
ap: app.Application
def __init__(self, prefix: str, ap: app.Application):
self.prefix = prefix
2024-01-29 21:58:47 +08:00
self.ap = ap
2024-01-29 21:58:47 +08:00
async def _do(
self,
method: str,
path: str,
data: dict = None,
params: dict = None,
2023-12-21 17:03:58 +08:00
headers: dict = {},
**kwargs,
):
2024-03-03 16:34:59 +08:00
"""
执行请求
"""
self._runtime_info["account_id"] = "-1"
2024-01-29 21:58:47 +08:00
url = self.prefix + path
data = json.dumps(data)
headers["Content-Type"] = "application/json"
2024-01-31 00:02:19 +08:00
2024-01-29 21:58:47 +08:00
try:
async with aiohttp.ClientSession() as session:
async with session.request(
method, url, data=data, params=params, headers=headers, **kwargs
2024-01-29 21:58:47 +08:00
) as resp:
self.ap.logger.debug("data: %s", data)
2024-01-31 00:02:19 +08:00
self.ap.logger.debug("ret: %s", await resp.text())
2023-12-21 17:03:58 +08:00
2024-01-29 21:58:47 +08:00
except Exception as e:
self.ap.logger.debug(f"上报失败: {e}")
2024-01-29 21:58:47 +08:00
async def do(
self,
method: str,
path: str,
data: dict = None,
params: dict = None,
headers: dict = {},
**kwargs,
2024-01-29 21:58:47 +08:00
) -> asyncio.Task:
"""执行请求"""
return self.ap.task_mgr.create_task(
self._do(method, path, data, params, headers, **kwargs),
kind="telemetry-operation",
name=f"{method} {path}",
2024-11-16 12:40:57 +08:00
scopes=[core_entities.LifecycleControlScope.APPLICATION],
).task
2024-10-22 18:09:18 +08:00
def gen_rid(self):
"""生成一个请求 ID"""
return str(uuid.uuid4())
def basic_info(self):
"""获取基本信息"""
basic_info = APIGroup._basic_info.copy()
basic_info["rid"] = self.gen_rid()
2023-12-21 17:03:58 +08:00
return basic_info
def runtime_info(self):
"""获取运行时信息"""
return APIGroup._runtime_info