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 httpEntity = new HttpEntity<>(JSONObject.toJSONString(params), headers); RestTemplate rst = new RestTemplate(); ResponseEntity 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("/")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("/")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 &更多信息請關注:@軟件老王,關注不迷路,軟件老王和他的IT朋友們,分享一些他們的技術見解和生活故事。
總結
以上是生活随笔為你收集整理的java 调用python_Java平台如何调用Python平台?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 范文100篇(2)
- 下一篇: FlinkAPI_Environment