springboot如何调用python程序
问题描述:
要做一个网站 后端springboot 需要把数据库里的数据拿出来用一个python程序调用然后把分析结果存到数据库里 目前只有用springboot+vue做了一个基本的网站的经验 没有像这种 多语言的 主要就是调用python这块 想问这要依赖哪些技术要补充哪些知识 是微服务相关的吗
答
可以用Http请求调用啊,只要Python端提供一个对外开放的接口:
比如:
@Resource
private RestTemplate restTemplate;
/**
* java 端调用Python端POST接口
*
* @param pyRequest java 端调用Python端接口的入参
* @return PyResp python端接口返回给java端的数据
*/
public PyResp pyRunDemo(final PyRequest pyRequest) {
HttpHeaders headers = new HttpHeaders();
// pyToken: 访问Python接口的授权token
headers.add("Authorization", pyToken);
headers.setContentType(MediaType.APPLICATION_JSON);
// Python端提供访问的接口url
final String url = " http://www.xxxx/upd/py";
log.info("pyRunDemo:[URL:{}]", url);
HttpEntity<PyRequest> request = new HttpEntity<>(PyRequest, headers);
// 该请求为post请求,参数为body传参
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
String json = response.getBody();
return parseObject(json, PyResp.class);
}