Spring Boot优雅调用Python:两种方法详解
Spring Boot 优雅调用 Python:两种方法详解
在开发过程中,您可能需要在 Spring Boot 项目中调用 Python 代码来完成某些特定的任务。本文将介绍两种常见的调用方法,并提供示例代码供您参考。
1. 使用 subprocess 库直接执行 Python 脚本
这种方法简单直接,您可以在 Spring Boot 的 Controller 中使用 Python 的 subprocess 库直接执行 Python 脚本。
示例代码:
@RequestMapping("/test")
public String test() throws IOException {
String[] cmd = new String[]{"python", "/path/to/python/script.py"};
Process process = Runtime.getRuntime().exec(cmd);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
String output = "";
String line = null;
while ((line = stdInput.readLine()) != null) {
output += line + "\n";
}
return output;
}
2. 使用 Flask 框架搭建 API 进行交互
如果您需要更灵活的交互方式,可以使用 Flask 框架搭建一个简单的 API,并在 Spring Boot 中调用 API。
Python 代码 (Flask API):
from flask import Flask, request
app = Flask(__name__)
@app.route('/api')
def api():
# 处理请求参数
arg1 = request.args.get('arg1')
arg2 = request.args.get('arg2')
# 调用 Python 函数处理数据
result = python_function(arg1, arg2)
# 返回结果
return result
if __name__ == '__main__':
app.run(debug=True)
Spring Boot 代码 (调用 API):
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:5000/api?arg1=value1&arg2=value2";
String result = restTemplate.getForObject(url, String.class);
其中,value1 和 value2 是传递给 Python 函数的参数。
总结
本文介绍了两种在 Spring Boot 项目中调用 Python 代码的方法,您可以根据实际情况选择合适的方法。希望本文能够帮助您在开发过程中更加便捷地实现 Spring Boot 与 Python 的协同工作。
原文地址: https://www.cveoy.top/t/topic/nEXA 著作权归作者所有。请勿转载和采集!