4
用jython实现java调用python
source link: http://www.blogjava.net/lzqdiy/archive/2023/05/20/451087.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
用jython实现java调用python
- 在Eclipse中创建springboot工程(maven)
- 配置pom.xml<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
</dependency>
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-slim</artifactId>
<version>2.7.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project> - 编写python代码
/src/main/resources/case.pyclass RequestObj:
def __init__(self,requestId):
self.requestid=requestId
class ResponseObj:
def __init__(self,apiId):
self.apiId=apiId
def testAPI(requestObj):
if requestObj.requestId == "1" :
responseObj=ResponseObj("/test/1")
elif requestObj.requestId == "2" :
responseObj=ResponseObj("/test/2")
else:
responseObj=ResponseObj("/test")
return responseObj - 编写java代码
/src/main/java/com/example/demo/json/Request.javapackage com.example.demo.json;/src/main/java/com/example/demo/json/Response.java
public class Request {
private String requsetId;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRequsetId() {
return requsetId;
}
public void setRequsetId(String requsetId) {
this.requsetId = requsetId;
}
}package com.example.demo.json;/src/main/java/com/example/demo/RestAPIController.java
public class Response {
private String apiId;
public String getApiId() {
return apiId;
}
public void setApiId(String apiId) {
this.apiId = apiId;
}
}package com.example.demo;
import java.io.IOException;
import org.python.core.PyFunction;
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.util.PythonInterpreter;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.json.Request;
import com.example.demo.json.Response;
@RestController
public class RestAPIController {
private static PythonInterpreter interpreter;
private static Resource resource = new ClassPathResource("case.py");
private static String path;
static {
interpreter = new PythonInterpreter();
try {
path = resource.getFile().getPath();
} catch (IOException e) {
e.printStackTrace();
}
}
private Response callPythonFunc(String funcName, Request request) {
interpreter.execfile(path);
PyObject requestObj = interpreter.get("RequestObj", PyObject.class);
requestObj.__setattr__("requestId", new PyString(request.getRequsetId()));
PyFunction function = interpreter.get(funcName, PyFunction.class);
PyObject responseObj = function.__call__(requestObj);
String apiId = responseObj.__getattr__("apiId").toString();
Response response = new Response();
response.setApiId(apiId);
return response;
}
@GetMapping("/test/get")
public String test1() {
Request request = new Request();
request.setRequsetId("1");
Response response = callPythonFunc("testAPI", request);
return response.getApiId();
}
@PostMapping("/test/post")
public Response test2(@RequestBody Request request) {
Response response = callPythonFunc("testAPI", request);
return response;
}
} - 运行springboot应用程序,console信息如下/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \\\/ ___)| |_)| | | | | || (_| | ) ) ) )' |____| .__|_| |_|_| |_\__, | / / / /=========|_|==============|___/=/_/_/_/:: Spring Boot :: (v3.0.5)2023-05-20T23:07:51.546+09:00 INFO 17548 --- [ main] com.example.demo.DemoApplication : Starting DemoApplication using Java 17.0.6 with PID 17548 (D:\pleiades\workspace\demo\target\classes started by lzqdi in D:\pleiades\workspace\demo)2023-05-20T23:07:51.550+09:00 INFO 17548 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to 1 default profile: "default"2023-05-20T23:07:52.760+09:00 INFO 17548 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)2023-05-20T23:07:52.777+09:00 INFO 17548 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]2023-05-20T23:07:52.778+09:00 INFO 17548 --- [ main] o.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/10.1.7]2023-05-20T23:07:52.904+09:00 INFO 17548 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext2023-05-20T23:07:52.908+09:00 INFO 17548 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1286 ms2023-05-20T23:07:55.673+09:00 INFO 17548 --- [ main] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page: class path resource [static/index.html]2023-05-20T23:07:55.832+09:00 INFO 17548 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''2023-05-20T23:07:55.846+09:00 INFO 17548 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 4.604 seconds (process running for 5.36)2023-05-20T23:08:36.469+09:00 INFO 17548 --- [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'2023-05-20T23:08:36.469+09:00 INFO 17548 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'2023-05-20T23:08:36.474+09:00 INFO 17548 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 5 ms
- 启动Postman进行测试■项目文件构成如下
posted on 2023-05-20 22:54 我为J狂 阅读(8) 评论(0) 编辑 收藏 所属分类: 开源框架
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK