删除冗余的函数

This commit is contained in:
jingrow 2025-10-26 23:05:26 +08:00
parent 9c8fb19ed8
commit ee9fa7e20a
2 changed files with 13 additions and 148 deletions

View File

@ -3,7 +3,7 @@ Jingrow Local 应用安装 API
提供本地应用安装管理等功能
"""
from fastapi import APIRouter, HTTPException, Request, UploadFile, File, Form
from fastapi import APIRouter, HTTPException, UploadFile, File, Form, Request
from typing import Dict, Any, List, Optional
import logging
import tempfile
@ -15,8 +15,8 @@ import json
import shutil
import re
from jingrow.utils.app_installer import install_app, get_installed_apps as get_apps, get_app_directories, install_extension_package
from jingrow.utils.jingrow_api import log_info, log_error
from jingrow.utils.app_installer import install_app, get_installed_apps as get_apps, get_app_directories
from jingrow.utils.jingrow_api import get_jingrow_api_headers
from jingrow.utils.auth import get_jingrow_cloud_url, get_jingrow_cloud_api_headers, get_jingrow_cloud_api_url, get_jingrow_api_headers
from jingrow.config import Config
@ -77,7 +77,6 @@ def _import_app_package_and_pagetypes(app_name: str, install_result: Dict[str, A
@router.post("/jingrow/install/upload")
async def install_app_from_upload(
request: Request,
file: UploadFile = File(...),
app_name: Optional[str] = Form(None)
):
@ -164,11 +163,11 @@ async def install_app_from_upload(
headers=get_jingrow_api_headers(),
timeout=60
)
except Exception as e:
log_error(f"同步应用文件失败: {str(e)}")
except Exception:
pass
except Exception as e:
log_error(f"更新数据库失败: {str(e)}")
except Exception:
pass
return result
else:
@ -527,71 +526,6 @@ async def get_app_info(request: Request, app_name: str):
raise HTTPException(status_code=500, detail=str(e))
async def _install_extension_package_in_api(package_path: str, original_filename: str) -> Dict[str, Any]:
"""保存扩展包并立即安装"""
import shutil
import requests
try:
current = Path(__file__).resolve()
if 'jingrow-framework' in str(current):
jingrow_bench_path = Path('/home/jingrow/jingrow-bench')
else:
project_root = current.parents[6] if current.parts.count('apps') > 1 else current.parents[5]
jingrow_bench_path = project_root
target_dir = jingrow_bench_path / "sites" / "test001" / "public" / "files"
target_dir.mkdir(parents=True, exist_ok=True)
target_path = target_dir / original_filename
shutil.copy2(package_path, target_path)
# 立即调用 jlocal API 安装扩展包
try:
from jingrow.utils.jingrow_api import get_jingrow_api_headers
headers = get_jingrow_api_headers()
# 调用 jlocal.install_package
api_url = f"{Config.jingrow_server_url}/api/action/jingrow.ai.utils.jlocal.install_package"
file_url = f"/files/{original_filename}"
response = requests.post(
api_url,
json={'package_file_url': file_url},
headers=headers,
timeout=60
)
if response.status_code == 200:
result = response.json()
if result.get('message', {}).get('success'):
return {
'success': True,
'message': f'扩展包安装成功',
'package_name': result.get('message', {}).get('package_name'),
'file_url': file_url,
'imported_files': result.get('message', {}).get('imported_files', []),
'file_count': result.get('message', {}).get('file_count', 0)
}
else:
return {'success': False, 'error': result.get('message', {}).get('error', '未知错误')}
else:
return {'success': False, 'error': f'API调用失败: HTTP {response.status_code}'}
except Exception:
return {
'success': True,
'message': f'扩展包已保存到 public/files 目录',
'file_url': f'/files/{original_filename}',
'file_path': str(target_path),
'note': '文件已上传,请手动在 jingrow 应用中使用 Package Import 功能导入'
}
except Exception as e:
return {'success': False, 'error': str(e)}
async def _remove_from_database(app_name: str) -> Dict[str, Any]:
"""从数据库中删除应用记录"""
try:
@ -722,63 +656,6 @@ async def get_app_meta():
raise HTTPException(status_code=500, detail=f"获取元数据失败: {str(e)}")
@router.post("/jingrow/install-extension")
async def install_extension_package_api(request: Request, file: UploadFile = File(...)):
"""安装扩展包到数据库"""
try:
log_info(f"开始处理上传的扩展包: {file.filename}")
if not file.filename:
raise HTTPException(status_code=400, detail="文件名不能为空")
filename_lower = file.filename.lower()
if not filename_lower.endswith(('.tar.gz', '.tgz', '.gz')):
raise HTTPException(status_code=400, detail=f"只支持TAR.GZ格式的扩展包当前文件: {filename_lower}")
content = await file.read()
if not content:
raise HTTPException(status_code=400, detail="文件内容为空")
# 使用标准文件上传接口
from jingrow.utils.jingrow_api import upload_file_to_jingrow, get_jingrow_api_headers
import requests
upload_result = upload_file_to_jingrow(content, file.filename)
if not upload_result.get('success'):
raise HTTPException(status_code=400, detail=upload_result.get('error', '文件上传失败'))
file_url = upload_result['file_url']
api_url = f"{Config.jingrow_server_url}/api/action/jingrow.ai.utils.jlocal.install_package"
headers = get_jingrow_api_headers()
response = requests.post(
api_url,
json={'package_file_url': file_url},
headers=headers,
timeout=60
)
if response.status_code == 200:
result_data = response.json()
if result_data.get('message', {}).get('success'):
return {
'success': True,
'package_name': result_data['message']['package_name'],
'file_url': file_url,
'file_count': result_data['message'].get('file_count', 0)
}
else:
raise HTTPException(status_code=400, detail=result_data.get('message', {}).get('error', '未知错误'))
else:
raise HTTPException(status_code=500, detail=f'安装API调用失败: HTTP {response.status_code}')
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@router.post("/jingrow/upload-image")
async def upload_image(file: UploadFile = File(...)):
"""上传应用图片"""

View File

@ -16,7 +16,7 @@ from functools import wraps
import logging
from jingrow.config import Config
from jingrow.utils.jingrow_api import log_info, log_error
from jingrow.utils.jingrow_api import get_jingrow_api_headers
logger = logging.getLogger(__name__)
@ -28,7 +28,6 @@ def handle_errors(func):
try:
return func(*args, **kwargs)
except Exception as e:
log_error(f"{func.__name__} 失败: {str(e)}")
return {'success': False, 'error': str(e)}
return wrapper
@ -213,8 +212,8 @@ def cleanup_temp_dir(temp_dir: str):
try:
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
except Exception as e:
log_error(f"清理临时目录失败: {str(e)}")
except Exception:
pass
def is_app_installed(app_name: str) -> bool:
@ -268,7 +267,6 @@ def install_app(uploaded_file_path: str, app_name: str = None) -> Dict[str, Any]
Dict: 安装结果
"""
try:
log_info(f"开始安装应用包: {uploaded_file_path}")
# 验证文件
if not os.path.exists(uploaded_file_path):
@ -345,7 +343,6 @@ def install_app(uploaded_file_path: str, app_name: str = None) -> Dict[str, Any]
}
except Exception as e:
log_error(f"安装应用失败: {str(e)}")
return {'success': False, 'error': str(e)}
@ -360,7 +357,6 @@ def install_extension_package(package_path: str) -> Dict[str, Any]:
Dict: 安装结果
"""
try:
log_info(f"开始安装扩展包: {package_path}")
# 验证文件
if not os.path.exists(package_path):
@ -435,7 +431,6 @@ def install_extension_package(package_path: str) -> Dict[str, Any]:
if os.path.isdir(module_path):
files = get_pg_files(files, module_path)
log_info(f"找到 {len(files)} 个 pagetype 文件待导入")
# 导入所有文件
imported_files = []
@ -443,14 +438,11 @@ def install_extension_package(package_path: str) -> Dict[str, Any]:
try:
import_file_by_path(file, force=True, ignore_version=True)
imported_files.append(file)
except Exception as e:
log_error(f"导入文件失败 {file}: {str(e)}")
# 继续导入其他文件,不中断
except Exception:
pass
# 清理临时文件
cleanup_temp_dir(temp_dir)
log_info(f"扩展包 {package_name} 安装成功,导入了 {len(imported_files)} 个文件")
return {
'success': True,
'message': f'扩展包 {package_name} 安装成功',
@ -461,11 +453,7 @@ def install_extension_package(package_path: str) -> Dict[str, Any]:
except Exception as e:
cleanup_temp_dir(temp_dir)
import traceback
error_detail = traceback.format_exc()
log_error(f"导入失败: {str(e)}")
return {'success': False, 'error': f'导入失败: {str(e)}', 'detail': error_detail}
return {'success': False, 'error': str(e)}
except Exception as e:
log_error(f"安装扩展包失败: {str(e)}")
return {'success': False, 'error': str(e)}