java执行python代码知识,java远程调用python脚本讲解看看

1. 问题描述

Java平台要调用Pyhon平台已有的算法,为了减少耦合度,采用Pyhon平台提供Restful 接口,Java平台负责来调用,采用Http+Json格式交互。

2. 解决方案

2.1 JAVA平台侧

2.1.1 项目代码

public static String invokeAlgorithm(String url, HashMap params) throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8")); headers.add("Accept", MediaType.APPLICATION_JSON.toString()); HttpEntity<String> httpEntity = new HttpEntity<>(JSONObject.toJSONString(params), headers); RestTemplate rst = new RestTemplate(); ResponseEntity<String> stringResponseEntity = rst.postForEntity(url, httpEntity, String.class); return stringResponseEntity.getBody(); }

2.1.2 代码解析

两个入参:url为Python提供restful调用方法;params参数,项目中参数使用了map,然后将map转成了Json,与Python服务器约定Json格式传输。

2.2 python平台侧

经过反复调研与深思熟虑的考虑后,决定采用flask提供Rest接口, flask 是一款非常流行的python web框架,微框架、简洁,社区活跃等。(其实是因为安装的Anaconda自带了flask,一配置一启动好了,就是这么巧)

2.2.1 项目代码

# -*- coding: utf-8 -*-from flask import Flask, request, send_from_directoryfrom k_means import execapp = Flask(__name__)import logging@app.route('/')def index(): return "Hello, World!"# k-means算法@app.route('/getKmeansInfoByPost', methods=['POST'])def getKmeansInfoByPost(): try: result = exec(request.get_json()) except IndexError as e: logging.error(str(e)) return 'exception:' + str(e) except KeyError as e: logging.error(str(e)) return 'exception:' + str(e) except ValueError as e: logging.error(str(e)) return 'exception:' + str(e) except Exception as e: logging.error(str(e)) return 'exception:' + str(e) else: return result@app.route("/<path:filename>")def getImages(filename): return send_from_directory(dirpath, filename, as_attachment=True)if __name__ == '__main__': app.run(host="0.0.0.0", port=5000, debug=True)

2.2.2 代码解析

代码为真实项目示例,去掉了一些配置而已,示例中包含三个方法,分别说一下

(1)最基本Rest接口:helloword

# -*- coding: utf-8 -*-from flask import Flaskapp = Flask(__name__)@app.route('/')def index(): return "Hello, World!"if __name__ == '__main__': app.run(host="0.0.0.0", port=5000, debug=True)

(2)调用其他python文件的Rest接口

# -*- coding: utf-8 -*-from flask import Flask, requestfrom k_means import execapp = Flask(__name__)import logging# k-means算法@app.route('/getKmeansInfoByPost', methods=['POST'])def getKmeansInfoByPost(): try: result = exec(request.get_json()) except IndexError as e: logging.error(str(e)) return 'exception:' + str(e) except KeyError as e: logging.error(str(e)) return 'exception:' + str(e) except ValueError as e: logging.error(str(e)) return 'exception:' + str(e) except Exception as e: logging.error(str(e)) return 'exception:' + str(e) else: return resultif __name__ == '__main__': app.run(host="0.0.0.0", port=5000, debug=True)

说明:1.接收POST方法;2. 从request获取java传过来的参数,对应上面的java调用代码

(3) 文件下载Rest接口

# -*- coding: utf-8 -*-from flask import Flask, send_from_directoryapp = Flask(__name__)@app.route("/<path:filename>")def getImages(filename): return send_from_directory(dirpath, filename, as_attachment=True)if __name__ == '__main__': app.run(host="0.0.0.0", port=5000, debug=True)

说明:1.还是flask框架提供的:send_from_directory

2.dirpath目录,一般可以给个固定存放目录,调用的时候只用给文件名称就可以直接下载对应文件。

2.3 Linux服务器启动python服务

nohup python restapi.py &

  • 72 views
    A+
发布日期:2021年08月27日 11:00:00  所属分类:知识经验
标签: