Files
CKB-Interface/application/store/create_and_move_agent.py
2026-03-24 10:39:16 +08:00

231 lines
8.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""自动创建Agent管理目录并移动接口"""
import sys
import requests
import json
import time
sys.stdout.reconfigure(encoding='utf-8')
TOKEN = "afxp_fa4137GfIzJtlOCeQHjpCXc83SFWmeAOrZnq"
PROJECT_ID = "6037107"
PARENT_FOLDER_ID = "78015216" # 门店端-新版
AGENT_API_IDS = [415861964, 415861967] # 已上传的Agent接口ID
headers = {
"X-Apifox-Api-Version": "2024-03-28",
"Authorization": f"Bearer {TOKEN}",
"Content-Type": "application/json; charset=utf-8"
}
print("=" * 80)
print("自动创建Agent管理目录并移动接口")
print("=" * 80)
# 步骤1: 检查是否已存在Agent管理目录
print("\n[1/4] 检查现有目录...")
response = requests.get(
f"https://api.apifox.com/api/v1/projects/{PROJECT_ID}/api-tree-list",
headers=headers
)
agent_folder_id = None
if response.status_code == 200:
tree_data = response.json().get('data', [])
def find_agent_folder(items):
for item in items:
if item.get('type') == 'apiDetailFolder':
folder = item.get('folder', {})
if item.get('name') == 'Agent管理' and folder.get('parentId') == int(PARENT_FOLDER_ID):
return folder.get('id')
for child in item.get('children', []):
result = find_agent_folder([child])
if result:
return result
return None
agent_folder_id = find_agent_folder(tree_data)
if agent_folder_id:
print(f" ✓ 找到现有'Agent管理'目录 (ID: {agent_folder_id})")
else:
print(f" ✗ 未找到'Agent管理'目录,开始创建...")
# 步骤2: 尝试多种方法创建目录
print("\n[2/4] 尝试创建目录...")
# 方法1: 使用 api-details-folders 端点(最常用)
create_methods = [
{
"name": "api-details-folders",
"url": f"https://api.apifox.com/api/v1/projects/{PROJECT_ID}/api-details-folders",
"data": {
"name": "Agent管理",
"parentId": int(PARENT_FOLDER_ID)
}
},
{
"name": "folders (with type)",
"url": f"https://api.apifox.com/api/v1/projects/{PROJECT_ID}/folders",
"data": {
"name": "Agent管理",
"parentId": int(PARENT_FOLDER_ID),
"type": "apiDetailFolder"
}
},
{
"name": "folders (simple)",
"url": f"https://api.apifox.com/api/v1/projects/{PROJECT_ID}/folders",
"data": {
"name": "Agent管理",
"parentId": int(PARENT_FOLDER_ID)
}
}
]
for method in create_methods:
print(f"\n 尝试方法: {method['name']}")
try:
create_resp = requests.post(
method['url'],
headers=headers,
json=method['data'],
timeout=10
)
print(f" 状态码: {create_resp.status_code}")
if create_resp.status_code == 200:
try:
result = create_resp.json()
if result.get('success') and 'data' in result:
agent_folder_id = result['data'].get('id')
print(f" ✓ 成功创建目录 (ID: {agent_folder_id})")
break
else:
print(f" ✗ 响应: {json.dumps(result, ensure_ascii=False)}")
except json.JSONDecodeError:
# 检查是否是重定向响应
if 'window.location.href' in create_resp.text:
print(f" ✗ API重定向可能被限制")
else:
print(f" ✗ 非JSON响应: {create_resp.text[:100]}")
elif create_resp.status_code == 201:
# 201 Created
try:
result = create_resp.json()
agent_folder_id = result.get('id') or result.get('data', {}).get('id')
if agent_folder_id:
print(f" ✓ 成功创建目录 (ID: {agent_folder_id})")
break
except:
print(f" ✗ 无法解析响应")
else:
print(f" ✗ HTTP {create_resp.status_code}: {create_resp.text[:200]}")
except Exception as e:
print(f" ✗ 异常: {str(e)}")
time.sleep(0.5)
# 如果所有方法都失败尝试使用导入OpenAPI的方式
if not agent_folder_id:
print("\n 尝试方法: OpenAPI导入带目录结构")
# 这个方法需要先准备OpenAPI文件暂时跳过
print(" ⚠️ 需要准备OpenAPI文件跳过此方法")
# 步骤3: 如果创建成功,移动接口
if agent_folder_id:
print(f"\n[3/4] 移动接口到'Agent管理'目录 (ID: {agent_folder_id})...")
print("-" * 80)
success_count = 0
fail_count = 0
for i, api_id in enumerate(AGENT_API_IDS, 1):
print(f"\n [{i}/{len(AGENT_API_IDS)}] 移动接口 {api_id}...")
try:
move_resp = requests.patch(
f"https://api.apifox.com/api/v1/projects/{PROJECT_ID}/http-apis/{api_id}",
headers=headers,
json={"folderId": int(agent_folder_id)},
timeout=10
)
if move_resp.status_code == 200:
result = move_resp.json()
if result.get('success'):
success_count += 1
print(f" ✓ 移动成功")
else:
fail_count += 1
print(f" ✗ 失败: {result.get('errorMessage', '未知错误')}")
else:
fail_count += 1
print(f" ✗ HTTP {move_resp.status_code}")
print(f" {move_resp.text[:200]}")
except Exception as e:
fail_count += 1
print(f" ✗ 异常: {str(e)}")
time.sleep(0.3)
# 步骤4: 验证结果
print(f"\n[4/4] 验证结果...")
verify_resp = requests.get(
f"https://api.apifox.com/api/v1/projects/{PROJECT_ID}/api-tree-list",
headers=headers
)
if verify_resp.status_code == 200:
tree_data = verify_resp.json().get('data', [])
agent_folder = None
def find_folder(items):
for item in items:
if item.get('type') == 'apiDetailFolder':
folder = item.get('folder', {})
if folder.get('id') == agent_folder_id:
return item
for child in item.get('children', []):
result = find_folder([child])
if result:
return result
return None
agent_folder = find_folder(tree_data)
if agent_folder:
api_count = len([c for c in agent_folder.get('children', []) if c.get('type') == 'apiDetail'])
print(f" ✓ 目录存在,包含 {api_count} 个接口")
else:
print(f" ⚠️ 目录存在但无法在树中找到")
print("\n" + "=" * 80)
print("完成!")
print("=" * 80)
print(f"✓ 成功移动: {success_count} 个接口")
print(f"✗ 失败: {fail_count} 个接口")
if success_count > 0:
print(f"\n✨ Agent接口已整理到'Agent管理'目录")
print(f"📁 目录ID: {agent_folder_id}")
print(f"🌐 访问查看: https://app.apifox.com/project/{PROJECT_ID}")
else:
print("\n" + "=" * 80)
print("⚠️ 无法自动创建目录")
print("=" * 80)
print("\n可能的原因:")
print("1. Apifox API对目录创建有限制")
print("2. Token权限不足")
print("3. 需要使用Web界面手动创建")
print("\n建议操作:")
print("1. 打开 https://app.apifox.com/project/6037107")
print("2. 在'门店端-新版'下创建'Agent管理'目录")
print("3. 运行: python move_to_agent_folder.py <目录ID>")
print("\n" + "=" * 80)