兼容金山文档流式返回与新版CLI格式
This commit is contained in:
+44
-7
@@ -34,12 +34,41 @@ def _call_tool(tool: str, args: dict, token: str | None) -> dict:
|
|||||||
headers['Authorization'] = f'Bearer {token}'
|
headers['Authorization'] = f'Bearer {token}'
|
||||||
request = urllib.request.Request(ENDPOINT, data=body, headers=headers, method='POST')
|
request = urllib.request.Request(ENDPOINT, data=body, headers=headers, method='POST')
|
||||||
with urllib.request.urlopen(request, timeout=15) as response:
|
with urllib.request.urlopen(request, timeout=15) as response:
|
||||||
payload = json.loads(response.read().decode('utf-8'))
|
raw = response.read().decode('utf-8')
|
||||||
|
payload = _parse_sse(raw)
|
||||||
if isinstance(payload, dict) and payload.get('code') not in (None, 0):
|
if isinstance(payload, dict) and payload.get('code') not in (None, 0):
|
||||||
raise RuntimeError(f"金山文档接口返回 {payload.get('code')}: {payload.get('message')}")
|
raise RuntimeError(f"金山文档接口返回 {payload.get('code')}: {payload.get('message')}")
|
||||||
return payload
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_sse(raw: str) -> dict:
|
||||||
|
"""兼容两种返回:纯 JSON 或 SSE 流(event:... / data:{...} 行)。"""
|
||||||
|
text = raw.strip()
|
||||||
|
if not text:
|
||||||
|
raise RuntimeError('金山文档接口返回空内容')
|
||||||
|
if text.startswith('{'):
|
||||||
|
return json.loads(text)
|
||||||
|
if 'data:' not in text:
|
||||||
|
raise RuntimeError(f'金山文档接口返回无法识别: {text[:120]}')
|
||||||
|
merged: dict = {}
|
||||||
|
for line in text.splitlines():
|
||||||
|
line = line.strip()
|
||||||
|
if not line.startswith('data:'):
|
||||||
|
continue
|
||||||
|
chunk = line[5:].strip()
|
||||||
|
if not chunk or chunk == '[DONE]':
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
item = json.loads(chunk)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
continue
|
||||||
|
if isinstance(item, dict):
|
||||||
|
merged.update(item)
|
||||||
|
if not merged:
|
||||||
|
raise RuntimeError(f'金山文档流式返回中没有有效数据: {text[:120]}')
|
||||||
|
return merged
|
||||||
|
|
||||||
|
|
||||||
def _parse_grid(cells: list[dict], row_to: int, col_to: int) -> list[list[str]]:
|
def _parse_grid(cells: list[dict], row_to: int, col_to: int) -> list[list[str]]:
|
||||||
grid = [['' for _ in range(col_to + 1)] for _ in range(row_to + 1)]
|
grid = [['' for _ in range(col_to + 1)] for _ in range(row_to + 1)]
|
||||||
for cell in cells:
|
for cell in cells:
|
||||||
@@ -49,6 +78,18 @@ def _parse_grid(cells: list[dict], row_to: int, col_to: int) -> list[list[str]]:
|
|||||||
return grid
|
return grid
|
||||||
|
|
||||||
|
|
||||||
|
def _unwrap(payload: dict, label: str) -> dict:
|
||||||
|
"""兼容新旧 CLI 返回格式:新版直接返回 detail,旧版包在 code/data 里。"""
|
||||||
|
if 'detail' in payload:
|
||||||
|
return payload['detail']
|
||||||
|
if payload.get('code') not in (None, 0):
|
||||||
|
raise RuntimeError(f"金山文档接口返回 {payload.get('code')}: {payload.get('message')}")
|
||||||
|
detail = (payload.get('data') or {}).get('detail')
|
||||||
|
if detail is None:
|
||||||
|
raise RuntimeError(f'金山文档返回格式无法识别({label})')
|
||||||
|
return detail
|
||||||
|
|
||||||
|
|
||||||
def fetch_rows(link_id: str = DEFAULT_LINK_ID) -> list[dict[str, str]]:
|
def fetch_rows(link_id: str = DEFAULT_LINK_ID) -> list[dict[str, str]]:
|
||||||
"""读取展厅使用登记表,返回去掉空行的记录列表。"""
|
"""读取展厅使用登记表,返回去掉空行的记录列表。"""
|
||||||
token = os.getenv('KINGSOFT_DOCS_TOKEN') or None
|
token = os.getenv('KINGSOFT_DOCS_TOKEN') or None
|
||||||
@@ -107,18 +148,14 @@ def fetch_via_cli(link_id: str = DEFAULT_LINK_ID) -> list[dict[str, str]]:
|
|||||||
if not cli:
|
if not cli:
|
||||||
raise RuntimeError('未找到金山文档命令行工具,请配置 KINGSOFT_DOCS_TOKEN 环境变量')
|
raise RuntimeError('未找到金山文档命令行工具,请配置 KINGSOFT_DOCS_TOKEN 环境变量')
|
||||||
payload = json.loads(_run_cli(cli, link_id))
|
payload = json.loads(_run_cli(cli, link_id))
|
||||||
if payload.get('code') != 0:
|
info = _unwrap(payload, '工作表信息')['sheetsInfo'][0]
|
||||||
raise RuntimeError(f"金山文档接口返回 {payload.get('code')}: {payload.get('message')}")
|
|
||||||
info = payload['data']['detail']['sheetsInfo'][0]
|
|
||||||
sheet_id = info['sheetId']
|
sheet_id = info['sheetId']
|
||||||
row_to = min(info.get('rowTo', 0), 1 + MAX_ROWS)
|
row_to = min(info.get('rowTo', 0), 1 + MAX_ROWS)
|
||||||
col_to = min(info.get('colTo', len(FIELDS) - 1), len(FIELDS) - 1)
|
col_to = min(info.get('colTo', len(FIELDS) - 1), len(FIELDS) - 1)
|
||||||
args = {'link_id': link_id, 'worksheet_id': sheet_id, 'range': {'rowFrom': 0, 'rowTo': row_to, 'colFrom': 0, 'colTo': col_to}}
|
args = {'link_id': link_id, 'worksheet_id': sheet_id, 'range': {'rowFrom': 0, 'rowTo': row_to, 'colFrom': 0, 'colTo': col_to}}
|
||||||
data_raw = _run_cli(cli, None, ['sheet', 'get-range-data', json.dumps(args, ensure_ascii=False)])
|
data_raw = _run_cli(cli, None, ['sheet', 'get-range-data', json.dumps(args, ensure_ascii=False)])
|
||||||
data = json.loads(data_raw)
|
data = json.loads(data_raw)
|
||||||
if data.get('code') != 0:
|
grid = _parse_grid(_unwrap(data, '选区数据')['rangeData'], row_to, col_to)
|
||||||
raise RuntimeError(f"金山文档接口返回 {data.get('code')}: {data.get('message')}")
|
|
||||||
grid = _parse_grid(data['data']['detail']['rangeData'], row_to, col_to)
|
|
||||||
header = grid[1] if len(grid) > 1 else FIELDS
|
header = grid[1] if len(grid) > 1 else FIELDS
|
||||||
records = []
|
records = []
|
||||||
for offset, row in enumerate(grid[2:]):
|
for offset, row in enumerate(grid[2:]):
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import json
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from server.hall_log import _parse_sse
|
||||||
|
|
||||||
|
|
||||||
|
class SseParsingTests(unittest.TestCase):
|
||||||
|
def test_plain_json_passes_through(self):
|
||||||
|
self.assertEqual(_parse_sse(json.dumps({'detail': {'x': 1}})), {'detail': {'x': 1}})
|
||||||
|
|
||||||
|
def test_sse_stream_is_merged(self):
|
||||||
|
raw = 'event:result\ndata:{"code":0,"data":{"detail":5}}\n\nevent:finish\n'
|
||||||
|
self.assertEqual(_parse_sse(raw), {'code': 0, 'data': {'detail': 5}})
|
||||||
|
|
||||||
|
def test_empty_raises(self):
|
||||||
|
with self.assertRaises(RuntimeError):
|
||||||
|
_parse_sse(' ')
|
||||||
|
with self.assertRaises(RuntimeError):
|
||||||
|
_parse_sse('event:finish\n')
|
||||||
Reference in New Issue
Block a user