134 lines
4.4 KiB
Python
134 lines
4.4 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
根据抓取的 API 自动生成 CLI 代码
|
|
"""
|
|
import json
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
def generate_cli_from_capture(capture_file: str):
|
|
"""从抓取的 API 生成 CLI 代码"""
|
|
|
|
with open(capture_file, 'r') as f:
|
|
apis = json.load(f)
|
|
|
|
# 分析并去重
|
|
endpoints = {}
|
|
for api in apis:
|
|
url = api['url']
|
|
method = api['method']
|
|
|
|
# 提取路径
|
|
if 'fumamx.com' in url:
|
|
path = url.split('fumamx.com')[-1]
|
|
else:
|
|
path = url
|
|
|
|
key = f"{method} {path.split('?')[0]}"
|
|
if key not in endpoints:
|
|
endpoints[key] = {
|
|
'method': method,
|
|
'path': path.split('?')[0],
|
|
'params': [],
|
|
'examples': []
|
|
}
|
|
|
|
# 提取查询参数
|
|
if '?' in path:
|
|
query = path.split('?')[1]
|
|
params = [p.split('=')[0] for p in query.split('&') if p]
|
|
endpoints[key]['params'].extend(params)
|
|
endpoints[key]['params'] = list(set(endpoints[key]['params']))
|
|
|
|
endpoints[key]['examples'].append(api)
|
|
|
|
# 生成分类
|
|
categories = {
|
|
'user': [],
|
|
'customer': [],
|
|
'email': [],
|
|
'order': [],
|
|
'workbench': [],
|
|
'other': []
|
|
}
|
|
|
|
for key, info in endpoints.items():
|
|
path = info['path'].lower()
|
|
if any(x in path for x in ['user', 'account', 'auth', 'login']):
|
|
categories['user'].append(info)
|
|
elif any(x in path for x in ['customer', 'crm', 'contact']):
|
|
categories['customer'].append(info)
|
|
elif any(x in path for x in ['email', 'mail', 'message']):
|
|
categories['email'].append(info)
|
|
elif any(x in path for x in ['order', 'trade', 'deal']):
|
|
categories['order'].append(info)
|
|
elif any(x in path for x in ['workbench', 'dashboard', 'home', 'main']):
|
|
categories['workbench'].append(info)
|
|
else:
|
|
categories['other'].append(info)
|
|
|
|
# 生成代码
|
|
print("=" * 70)
|
|
print("生成的 API 端点:")
|
|
print("=" * 70)
|
|
|
|
for cat_name, cat_apis in categories.items():
|
|
if cat_apis:
|
|
print(f"\n## {cat_name.upper()} ({len(cat_apis)} 个端点)")
|
|
for api in cat_apis:
|
|
params_str = ", ".join(api['params']) if api['params'] else "无"
|
|
print(f" {api['method']:6} {api['path']}")
|
|
print(f" 参数: {params_str}")
|
|
|
|
# 生成 client.py 代码
|
|
print("\n" + "=" * 70)
|
|
print("生成的 client.py 方法:")
|
|
print("=" * 70)
|
|
|
|
for cat_name, cat_apis in categories.items():
|
|
if cat_apis:
|
|
for api in cat_apis:
|
|
path = api['path']
|
|
method = api['method'].lower()
|
|
|
|
# 生成方法名
|
|
parts = path.strip('/').split('/')
|
|
func_name = '_'.join(parts[-2:]) if len(parts) >= 2 else parts[-1]
|
|
func_name = func_name.replace('-', '_').replace('.', '_')
|
|
|
|
if method == 'get':
|
|
print(f"""
|
|
def {func_name}(self{', ' + ', '.join([f'{p}=None' for p in api['params']]) if api['params'] else ''}):
|
|
\"\"\"{path}\"\"\"
|
|
params = {{{', '.join([f"'{p}': {p}" for p in api['params']])}}}
|
|
return self.get('{path}')""")
|
|
else:
|
|
print(f"""
|
|
def {func_name}(self, data=None):
|
|
\"\"\"{path}\"\"\"
|
|
return self.post('{path}', data=data)""")
|
|
|
|
# 保存结果
|
|
output = Path('/home/ubuntu/nanocode/fumamxCLI/discovered_apis.json')
|
|
with open(output, 'w') as f:
|
|
json.dump({
|
|
'endpoints': list(endpoints.values()),
|
|
'categories': {k: v for k, v in categories.items() if v}
|
|
}, f, ensure_ascii=False, indent=2)
|
|
|
|
print(f"\n✅ 结果已保存到: {output}")
|
|
|
|
|
|
if __name__ == '__main__':
|
|
if len(sys.argv) < 2:
|
|
print("Usage: python setup_apis.py <fumamx_apis.json>")
|
|
print("")
|
|
print("1. 在浏览器控制台运行 capture_api.js")
|
|
print("2. 操作页面后运行 exportFumamxAPIs()")
|
|
print("3. 下载 fumamx_apis.json 到本目录")
|
|
print("4. 运行: python setup_apis.py fumamx_apis.json")
|
|
sys.exit(1)
|
|
|
|
generate_cli_from_capture(sys.argv[1])
|