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_directory
from k_means import exec
app = 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 Flask
app = 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, request
from k_means import exec
app = 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 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__)
@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 &