first commit
This commit is contained in:
162
backend/app/services/templates/nodejs_http_service.js.j2
Normal file
162
backend/app/services/templates/nodejs_http_service.js.j2
Normal file
@@ -0,0 +1,162 @@
|
||||
|
||||
// Node.js HTTP服务包装器
|
||||
|
||||
const http = require('http');
|
||||
const url = require('url');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
// 服务配置
|
||||
const HOST = process.env.HOST || '{{host}}';
|
||||
const PORT = process.env.PORT || {{port}};
|
||||
const TIMEOUT = process.env.TIMEOUT || {{timeout}};
|
||||
|
||||
// 尝试导入算法模块
|
||||
let algorithmModule = null;
|
||||
try {
|
||||
// 根据入口点导入算法
|
||||
if ("{{entry_point}}" === "") {
|
||||
// 尝试导入主要模块
|
||||
algorithmModule = require('./algorithm');
|
||||
} else {
|
||||
// 导入入口点
|
||||
algorithmModule = require('./{{entry_point}}');
|
||||
}
|
||||
console.log('算法模块导入成功');
|
||||
} catch (e) {
|
||||
console.error('算法模块导入失败:', e);
|
||||
algorithmModule = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 调用算法
|
||||
* @param {Object} requestData 请求数据
|
||||
* @returns {Object} 算法执行结果
|
||||
*/
|
||||
function callAlgorithm(requestData) {
|
||||
if (!algorithmModule) {
|
||||
throw new Error('算法模块未加载');
|
||||
}
|
||||
|
||||
// 尝试调用算法的主要函数
|
||||
try {
|
||||
if (algorithmModule.predict) {
|
||||
return algorithmModule.predict(requestData);
|
||||
} else if (algorithmModule.run) {
|
||||
return algorithmModule.run(requestData);
|
||||
} else if (algorithmModule.main) {
|
||||
return algorithmModule.main(requestData);
|
||||
} else {
|
||||
throw new Error('未找到算法执行函数');
|
||||
}
|
||||
} catch (e) {
|
||||
throw new Error(`算法执行失败: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理请求
|
||||
* @param {http.IncomingMessage} req 请求对象
|
||||
* @param {http.ServerResponse} res 响应对象
|
||||
*/
|
||||
function handleRequest(req, res) {
|
||||
const parsedUrl = url.parse(req.url, true);
|
||||
const pathname = parsedUrl.pathname;
|
||||
|
||||
// 设置响应头
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
|
||||
if (req.method === 'GET') {
|
||||
if (pathname === "{{health_check_path}}") {
|
||||
// 健康检查
|
||||
res.writeHead(200);
|
||||
res.end(JSON.stringify({ status: 'healthy', service: '{{project_name}}' }));
|
||||
} else if (pathname === '/info') {
|
||||
// 服务信息
|
||||
const info = {
|
||||
service: '{{project_name}}',
|
||||
version: '1.0.0',
|
||||
host: HOST,
|
||||
port: PORT,
|
||||
timeout: TIMEOUT,
|
||||
algorithm_loaded: algorithmModule !== null
|
||||
};
|
||||
res.writeHead(200);
|
||||
res.end(JSON.stringify(info));
|
||||
} else {
|
||||
// 404响应
|
||||
res.writeHead(404);
|
||||
res.end(JSON.stringify({ error: 'Not Found' }));
|
||||
}
|
||||
} else if (req.method === 'POST') {
|
||||
let body = '';
|
||||
|
||||
// 读取请求体
|
||||
req.on('data', chunk => {
|
||||
body += chunk.toString();
|
||||
});
|
||||
|
||||
req.on('end', () => {
|
||||
try {
|
||||
// 解析请求数据
|
||||
const requestData = JSON.parse(body);
|
||||
|
||||
// 记录请求开始时间
|
||||
const startTime = Date.now();
|
||||
|
||||
// 调用算法
|
||||
const result = callAlgorithm(requestData);
|
||||
|
||||
// 计算响应时间
|
||||
const responseTime = (Date.now() - startTime) / 1000;
|
||||
|
||||
// 构建响应
|
||||
const response = {
|
||||
success: true,
|
||||
result: result,
|
||||
response_time: responseTime.toFixed(4),
|
||||
message: '算法执行成功'
|
||||
};
|
||||
|
||||
// 发送响应
|
||||
res.writeHead(200);
|
||||
res.end(JSON.stringify(response));
|
||||
} catch (e) {
|
||||
// 构建错误响应
|
||||
const errorResponse = {
|
||||
success: false,
|
||||
error: e.message,
|
||||
message: '算法执行失败'
|
||||
};
|
||||
|
||||
// 发送错误响应
|
||||
res.writeHead(400);
|
||||
res.end(JSON.stringify(errorResponse));
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// 不支持的方法
|
||||
res.writeHead(405);
|
||||
res.end(JSON.stringify({ error: 'Method Not Allowed' }));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动服务
|
||||
*/
|
||||
function startServer() {
|
||||
const server = http.createServer(handleRequest);
|
||||
|
||||
server.listen(PORT, HOST, () => {
|
||||
console.log(`服务启动成功,监听地址: ${HOST}:${PORT}`);
|
||||
console.log(`健康检查地址: http://${HOST}:${PORT}{{health_check_path}}`);
|
||||
console.log(`服务信息地址: http://${HOST}:${PORT}/info`);
|
||||
});
|
||||
|
||||
server.on('error', (error) => {
|
||||
console.error('服务启动失败:', error);
|
||||
});
|
||||
}
|
||||
|
||||
// 启动服务
|
||||
startServer();
|
||||
166
backend/app/services/templates/python_http_service.py.j2
Normal file
166
backend/app/services/templates/python_http_service.py.j2
Normal file
@@ -0,0 +1,166 @@
|
||||
|
||||
# Python HTTP服务包装器
|
||||
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import time
|
||||
from http.server import HTTPServer, BaseHTTPRequestHandler
|
||||
|
||||
# 添加项目路径到Python路径
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
# 尝试导入算法模块
|
||||
try:
|
||||
# 根据入口点导入算法
|
||||
if "{{entry_point}}" == "":
|
||||
# 尝试导入主要模块
|
||||
import algorithm
|
||||
algorithm_module = algorithm
|
||||
else:
|
||||
# 动态导入入口点
|
||||
import importlib.util
|
||||
spec = importlib.util.spec_from_file_location("algorithm_module", "{{entry_point}}")
|
||||
algorithm_module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(algorithm_module)
|
||||
print("算法模块导入成功")
|
||||
except Exception as e:
|
||||
print(f"算法模块导入失败: {e}")
|
||||
algorithm_module = None
|
||||
|
||||
# 服务配置
|
||||
HOST = os.environ.get("HOST", "{{host}}")
|
||||
PORT = int(os.environ.get("PORT", "{{port}}"))
|
||||
TIMEOUT = int(os.environ.get("TIMEOUT", "{{timeout}}"))
|
||||
|
||||
class AlgorithmRequestHandler(BaseHTTPRequestHandler):
|
||||
"""算法请求处理器"""
|
||||
|
||||
def do_POST(self):
|
||||
"""处理POST请求"""
|
||||
try:
|
||||
# 读取请求体
|
||||
content_length = int(self.headers['Content-Length'])
|
||||
post_data = self.rfile.read(content_length)
|
||||
|
||||
# 解析请求数据
|
||||
request_data = json.loads(post_data.decode('utf-8'))
|
||||
|
||||
# 记录请求开始时间
|
||||
start_time = time.time()
|
||||
|
||||
# 调用算法
|
||||
result = self._call_algorithm(request_data)
|
||||
|
||||
# 计算响应时间
|
||||
response_time = time.time() - start_time
|
||||
|
||||
# 构建响应
|
||||
response = {
|
||||
"success": True,
|
||||
"result": result,
|
||||
"response_time": round(response_time, 4),
|
||||
"message": "算法执行成功"
|
||||
}
|
||||
|
||||
# 发送响应
|
||||
self.send_response(200)
|
||||
self.send_header('Content-type', 'application/json')
|
||||
self.end_headers()
|
||||
self.wfile.write(json.dumps(response).encode('utf-8'))
|
||||
|
||||
except Exception as e:
|
||||
# 构建错误响应
|
||||
error_response = {
|
||||
"success": False,
|
||||
"error": str(e),
|
||||
"message": "算法执行失败"
|
||||
}
|
||||
|
||||
# 发送错误响应
|
||||
self.send_response(400)
|
||||
self.send_header('Content-type', 'application/json')
|
||||
self.end_headers()
|
||||
self.wfile.write(json.dumps(error_response).encode('utf-8'))
|
||||
|
||||
def do_GET(self):
|
||||
"""处理GET请求"""
|
||||
if self.path == "{{health_check_path}}":
|
||||
# 健康检查
|
||||
self._handle_health_check()
|
||||
elif self.path == "/info":
|
||||
# 服务信息
|
||||
self._handle_info()
|
||||
else:
|
||||
# 404响应
|
||||
self.send_response(404)
|
||||
self.send_header('Content-type', 'application/json')
|
||||
self.end_headers()
|
||||
self.wfile.write(json.dumps({"error": "Not Found"}).encode('utf-8'))
|
||||
|
||||
def _call_algorithm(self, request_data):
|
||||
"""调用算法
|
||||
|
||||
Args:
|
||||
request_data: 请求数据
|
||||
|
||||
Returns:
|
||||
算法执行结果
|
||||
"""
|
||||
if algorithm_module is None:
|
||||
raise Exception("算法模块未加载")
|
||||
|
||||
# 尝试调用算法的主要函数
|
||||
try:
|
||||
# 检查是否有predict函数
|
||||
if hasattr(algorithm_module, 'predict'):
|
||||
return algorithm_module.predict(request_data)
|
||||
# 检查是否有run函数
|
||||
elif hasattr(algorithm_module, 'run'):
|
||||
return algorithm_module.run(request_data)
|
||||
# 检查是否有main函数
|
||||
elif hasattr(algorithm_module, 'main'):
|
||||
return algorithm_module.main(request_data)
|
||||
else:
|
||||
raise Exception("未找到算法执行函数")
|
||||
except Exception as e:
|
||||
raise Exception(f"算法执行失败: {e}")
|
||||
|
||||
def _handle_health_check(self):
|
||||
"""处理健康检查"""
|
||||
self.send_response(200)
|
||||
self.send_header('Content-type', 'application/json')
|
||||
self.end_headers()
|
||||
self.wfile.write(json.dumps({"status": "healthy", "service": "{{project_name}}"}).encode('utf-8'))
|
||||
|
||||
def _handle_info(self):
|
||||
"""处理服务信息请求"""
|
||||
info = {
|
||||
"service": "{{project_name}}",
|
||||
"version": "1.0.0",
|
||||
"host": HOST,
|
||||
"port": PORT,
|
||||
"timeout": TIMEOUT,
|
||||
"algorithm_loaded": algorithm_module is not None
|
||||
}
|
||||
|
||||
self.send_response(200)
|
||||
self.send_header('Content-type', 'application/json')
|
||||
self.end_headers()
|
||||
self.wfile.write(json.dumps(info).encode('utf-8'))
|
||||
|
||||
def run_server():
|
||||
"""启动服务"""
|
||||
server = HTTPServer((HOST, PORT), AlgorithmRequestHandler)
|
||||
print(f"服务启动成功,监听地址: {HOST}:{PORT}")
|
||||
print(f"健康检查地址: http://{HOST}:{PORT}{{health_check_path}}")
|
||||
print(f"服务信息地址: http://{HOST}:{PORT}/info")
|
||||
|
||||
try:
|
||||
server.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
print("服务停止")
|
||||
server.shutdown()
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_server()
|
||||
Reference in New Issue
Block a user