Java服务器调用Python服务器进行交互:基于Http协议的Restful风格调用(Springboot/FastApi)

实现Java服务器调用Python服务器进行交互以及数据传输,可采用以下方法,亲测有效:

  • 基于Restful风格进行请求调用:
  • 框架
    • Java服务器采用Springboot框架进行搭建服务
    • python服务器采用FastApi框架进行搭建服务
  • 思路:前端–>Java–>python–>Java–>前端
  • 代码设计:Axios->@PostMapping->请求Python(下文描述)–>@app.get/@app.Post
    • 请求Python方式:Java可以采用Spring框架的RestTemplate进行请求Python服务器,或者使用原生JavaEE进行HttpRequest请求访问Python服务器。
  • 以下将描述两种调用的方法:

1.基于RestTemplate进行请求Python服务器
Java:

 @GetMapping("/api/length")
    public String getAiAssistant(String text) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        text="我要喝咖啡!!";
        Map<String,String> requestBody =new HashMap<>();
        requestBody.put("text",text);
        requestBody.put("text2","再来一个~~~");
        // 设置请求体数据
//         requestBody = "{\"text\": \"" + text + "\"}";
//        String requestBody2 = "{\"text2\": \"" + text + "\"}";
        String url = "http://192.168.1.11:8000/api/length";
        String pythonUrl = jackieConfig.getPythonUrl();
        // 创建HttpEntity对象,将请求头和请求体封装起来
        //可以基于这个进行修改
//        HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
        HttpEntity<Map> requestEntity = new HttpEntity<>(requestBody, headers);
        System.out.println("requestEntity = " + requestEntity +"+类型:"+requestEntity.getClass());

        // 发送POST请求,并获取响应结果
        RestTemplate restTemplate = new RestTemplate();
        System.out.println("restTemplate = " + restTemplate+"+类型:"+restTemplate.getClass());
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);
        System.out.println("responseEntity = " + responseEntity +"+类型:"+responseEntity.getClass());
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            String response = responseEntity.getBody();
            System.out.println("response = " + response+"+类型:"+response.getClass());
            return response;
        } else {
            // 处理请求失败的情况
            return null;
        }
    }

python:

 # 通过响应体传递参数
@app.post("/api/length")
def get_length(data: dict):
    print(data)
    text = data["text"]
    length = len(text)
    return {"data": data}

2.基于HttpRequest进行请求Python服务器
Java:

 @PostMapping("/page")
    public String DocGeneration( String data) {
        data="我要喝咖啡!!";
        SysUser TenantUser = SecurityUtils.getLoginUser().getUser();
        SysTenant sysTenant = sysTenantService.selectSysTenantById(TenantUser.getTenantId());
        String apiKey = sysTenant.getApiKey();
        String apiStatus = String.valueOf(sysTenant.getApiStatus());
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("apiKey",apiKey);
        paramMap.put("model", apiStatus);
        paramMap.put("context", data);
        String stringbody =  String.valueOf(new JSONObject(paramMap));
        String responseBody =null;
        try
        {
            responseBody = HttpRequest.post(pythonUrl + "/docGeneration/page")
                    .header("Authorization", apiKey)
                    .header("Content-Type", "application/json")
                    .body(stringbody)
                    .execute()
                    .body();
            System.out.println("responseBody = " + responseBody);


        } catch (HttpException e) {
            return "出现了异常";
        } catch (ConvertException e) {
            return "出现了异常";
        }

        System.out.println("数据对接");
        return responseBody;



    }

java返回数据:
在这里插入图片描述

python返回数据:
在这里插入图片描述

Python:

class Data(BaseModel):
    apiKey: str
    context: str
    model: str

@app.post("/docGeneration/page")
async def docGeneration(data: Data):
    print(data)
    return {"data": data}


  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python 运维开发:基于 Kubernetes RESTful API 实现 Deployment 创建 Kubernetes是一个开源的容器编排平台,它提供了一种便捷的方式来部署、扩展和管理容器化应用。在运维开发中,我们经常需要使用Kubernetes的API来创建Deployment。 首先,我们需要使用Python中的requests库来与Kubernetes的API进行交互。我们可以使用`requests.get()`或`requests.post()`等方法来发送HTTP请求,对Kubernetes进行操作。 接下来,我们需要构造正确的API地址和API请求数据。Kubernetes的API地址是基于集群的,我们可以通过访问`https://api.example.com`来得到API根地址。然后我们需要通过构造不同的路径来进行不同的操作,比如创建Deployment、查看Deployment等。 对于创建Deployment,我们可以使用POST请求来发送Deployment的定义。我们可以定义Deployment的名称、容器镜像、副本数量等信息,然后将这些信息转换为JSON格式,作为请求的数据体,发送到`/apis/apps/v1/namespaces/{namespace}/deployments`路径。 示例代码如下: ```python import requests import json def create_deployment(namespace, name, image, replicas): api_url = "https://api.example.com" endpoint = f"{api_url}/apis/apps/v1/namespaces/{namespace}/deployments" headers = {"Content-Type": "application/json"} data = { "apiVersion": "apps/v1", "kind": "Deployment", "metadata": { "name": name }, "spec": { "replicas": replicas, "selector": { "matchLabels": { "app": name } }, "template": { "metadata": { "labels": { "app": name } }, "spec": { "containers": [ { "name": name, "image": image, "ports": [ { "containerPort": 80 } ] } ] } } } } response = requests.post(endpoint, headers=headers, json=data) if response.status_code == 201: print(f"Deployment {name} created successfully.") else: print(f"There was an error creating Deployment {name}: {response.json()}") # 调用示例 create_deployment("default", "my-deployment", "my-image:latest", 3) ``` 以上代码中,我们定义了一个名为`create_deployment`的函数,它接受Namespace名称、Deployment名称、容器镜像和副本数量作为参数。然后,我们使用这些参数构造出Deployment的定义,并发送POST请求,创建Deployment。 最后,我们可以根据返回的响应状态码来判断Deployment是否成功创建。如果返回状态码为201,表示创建成功,否则表示创建失败,并打印出相应的错误信息。 通过这种方法,我们可以使用Python来基于Kubernetes的RESTful API实现Deployment的创建。这样,我们就可以在运维开发中使用Python来自动化操作Kubernetes集群,提高部署效率和管理灵活性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值