java远程调用python脚本讲解 java执行python代码


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目录 , 一般可以给个固定存放目录 , 调用的时候只用给文件名称就可以直接下载对应文件 。


以上关于本文的内容,仅作参考!温馨提示:如遇健康、疾病相关的问题,请您及时就医或请专业人士给予相关指导!

「四川龙网」www.sichuanlong.com小编还为您精选了以下内容,希望对您有所帮助: