欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-21 18:37:58
1. 问题描述java平台要调用pyhon平台已有的算法,为了减少耦合度,采用pyhon平台提供restful 接口,java平台负责来调用,采用http+json格式交互。2. 解决方案2.1 ja...

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 &