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.String());
HttpEntity<String> httpEntity = new HttpEntity<>(JSONString(params), headers);
RestTemplate rst = new RestTemplate();
ResponseEntity<String> stringResponseEntity = rst.postForEntity(url, httpEntity, String.class);
Body();
}
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_directory
from k_means import exec
app = Flask(__name__)
import logging
@ute('/')
def index():
return "Hello, World!"
# k-means算法
@ute('/getKmeansInfoByPost', methods=['POST'])
def getKmeansInfoByPost():
try:
result = _json())
except IndexError as e:
<(str(e))
return 'exception:' + str(e)
except KeyError as e:
<(str(e))
return 'exception:' + str(e)
except ValueError as e:
<(str(e))
return 'exception:' + str(e)
except Exception as e:
<(str(e))
return 'exception:' + str(e)
else:
return result
@ute("/<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 代码解析
代码为真实项⽬⽰例,去掉了⼀些配置⽽已,⽰例中包含三个⽅法,分别说⼀下java python是什么意思
(1)最基本Rest接⼝:helloword
# -*- coding: utf-8 -*-
from flask import Flask
app = Flask(__name__)
@ute('/')
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, request
from k_means import exec
app = Flask(__name__)
import logging
# k-means算法
@ute('/getKmeansInfoByPost', methods=['POST'])
def getKmeansInfoByPost():
try:
result = _json())
except IndexError as e:
<(str(e))
return 'exception:' + str(e)
except KeyError as e:
<(str(e))
return 'exception:' + str(e)
except ValueError as e:
<(str(e))
return 'exception:' + str(e)
except Exception as e:
<(str(e))
return 'exception:' + str(e)
else:
return result
if __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_directory
app = Flask(__name__)
@ute("/<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 &
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论