如何在基于Java的Spring Boot项目中调用内部的Python服务

huangapple go评论157阅读模式
英文:

How to call an internal Python service for a Java-based Spring Boot project

问题

我有以下问题,我正在寻求更好的解决方法。

我需要在Spring Boot项目内部执行一个Python脚本。这个脚本应该相当简单,但是由其他人制作,如果可能的话,我希望避免需要修改它。

从我所理解的情况来看,我有两个选项:

  1. 从我的Java代码中执行一个shell命令,类似于这里所示的示例:
    https://www.baeldung.com/run-shell-command-in-java

使用这种方法,我可能需要处理操作系统识别脚本运行位置并进行处理。

  1. 使用Jython将Python代码嵌入到我的Java代码中,但我真的不知道它是如何工作的,而且很可能我会遇到兼容性问题(代码是其他人制作的,应该很简单,但最好是我不需要更改这段代码)。

那么你建议我采取哪种方式?

英文:

I have the following problem and I am asking for the better approach.

I have to execute a Python script from the inside of a Spring Boot project. The script should be pretty easy but was made by other people and if possible I want to avoid the needing of change it.

From what I have understand I have two options:

  1. From my Java code I execute a shell command, something like shown here:
    https://www.baeldung.com/run-shell-command-in-java

Using this approach probably I have to handle the operating system recognition of where my script run and deal with it.

  1. Using Jython to embedd Python code into my Java code but I really don't know how it works and if probably I will face compatibility code (the code was made from other people, it should be very easy but it is better if I have not to change something on this code).

So what way you suggest me?

答案1

得分: 3

更好的方法是将Python脚本视为一个外部服务,而不是要执行的文件。在这种情况下,我强烈建议使用Flask作为一个轻量级框架。

一个简单的Flask应用程序可能如下所示:

from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/')
def hello():
    # 在这里调用你的脚本方法
    return jsonify(success=True)

if __name__ == '__main__':
    app.run(debug=True)

在本地开发的情况下,你可以使用shell命令"python filename.py"来运行这个应用程序。默认情况下,你可以通过http://127.0.0.1:5000/调用这个服务,使用你喜欢的Java方法。

英文:

A better approach would be to treat the Python script as an external service to be called rather than a file to be executed. In this case, I would strongly advise Flask as a light-weight framework.

A simple flask application would look something like this:

from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/')
def hello():
    # Call your script method here
    return jsonify(success=True)

if __name__ == '__main__':
    app.run(debug=True)

In the case of local development, you can run this application with the shell command "python filename.py". By default, you can call this service by http://127.0.0.1:5000/ using the preferred Java method of yours.

huangapple
  • 本文由 发表于 2020年8月1日 02:47:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/63197508.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定