java调用python并且实现RESTAPI

  1. 在Eclipse中创建springboot工程(maven)

         

 

  1. 配置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-web</artifactId>
            </dependency>
            
            <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>
  2. 编写python代码  /src/main/resources/case.py
    class 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
  3. 编写java代码 /src/main/java/com/example/demo/json/Request.java
    package com.example.demo.json;
    
    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;
        }
    
    }

    /src/main/java/com/example/demo/json/Response.java

    package com.example.demo.json;
    
    public class Response {
        private String apiId;
    
        public String getApiId() {
            return apiId;
        }
    
        public void setApiId(String apiId) {
            this.apiId = apiId;
        }
        
    }

    /src/main/java/com/example/demo/RestAPIController.java

    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 test3(@RequestBody Request request) {
            Response response = callPythonFunc("testAPI", request);
            return response;
        }
    }
  4. 运行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 WebApplicationContext
2023-05-20T23:07:52.908+09:00 INFO 17548 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1286 ms
2023-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 测试RESTAPI~~~~~~~~~~~~

              ~~~~~~~~~~~~~程序构造如下~~~~~~~~~~~~~~~~~

              

 

posted @ 2023-05-19 22:24  我为P狂  阅读(139)  评论(0编辑  收藏  举报