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

来源:国外服务器 在您之前已被浏览:1 次
导读:目前正在解读《java执行python代码(java远程调用python脚本讲解)》的相关信息,《java执行python代码(java远程调用python脚本讲解)》是由用户自行发布的知识型内容!下面请观看由(国外主机 - www.2bp.net)用户发布《java执行python代码(java远程调用python脚本讲解)》的详细说明。
笨笨网美国主机,w ww.2 b p .n e t

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 &
笨笨网美国主机,w ww.2 b p .n e t
提醒:《java执行python代码(java远程调用python脚本讲解)》最后刷新时间 2025-03-21 11:16:55,本站为公益型个人网站,仅供个人学习和记录信息,不进行任何商业性质的盈利。如果内容、图片资源失效或内容涉及侵权,请反馈至,我们会及时处理。本站只保证内容的可读性,无法保证真实性,《java执行python代码(java远程调用python脚本讲解)》该内容的真实性请自行鉴别。