使用Swagger Codegen生成Python服务端客户端代码

使用的Swagger Codegen版本

swagger-codegen-cli-2.4.32.jar

生成代码

java -jar swagger-codegen-cli.jar generate -i http://xxx.xxx.xxx.xxx:xxxx/v2/api-docs -l python --artifact-id=get-sign-code-gen-python -o  ./getSignCodeGenPython

生成的目录结构如下图所示
在这里插入图片描述

环境配置

配置虚拟环境(virtualenv 可选)

我用的是virtualenv生成的虚拟环境运行的,其他虚拟化环境也一样,所以这里我只贴一下 virtualenv 的命令

$ virtualenv venv
$ source venv/bin/activate
$ pip install -r requirements.txt

然后默认生成的代码需要修改或者确认两个地方

修改第一个文件

路径为swagger_client/api/init.py
原来的DefaultApi路径是错误的,无法import,所以需要改成我下图这样
在这里插入图片描述

第二个文件

确认一下 DefaultApi 是否已经可以正常导入了
在这里插入图片描述

第三个文件

文件路径 swagger_client/configuration.py 可能需要将协议https改成http,否则会报SSL认证错误
在这里插入图片描述

开始测试

我们自己创建一个python文件,我这里叫testray.py,需要放在跟setup.py这个文件同级目录下,也就是最外层,添加如下内容

from __future__ import print_function
import swagger_client
from swagger_client.rest import ApiException
from pprint import pprint

# create an instance of the API class
api_instance = swagger_client.DefaultApi(swagger_client.ApiClient())
key = 'key_example' # str | key   这个key字段是非必要的

try:
    # 获取secret
    api_response = api_instance.get_secret_using_get(key) # 这里的get_secret_using_get请改成你们自己生成代码对应的方法,代码提示应该会显示有哪些方法的,不清楚的去 swagger_client/api/_api.py 这个文件的DefaultApi类下去找,有哪些方法
    pprint(api_response)
except ApiException as e:
    print("Exception when calling DefaultApi->get_secret_using_get: %s\n" % e)

此时我去执行这个文件,就会返回对应的接口结果了
在这里插入图片描述

好的,下面是一个通过 Swagger Codegen 生成 Python 代码的示例: 1. 首先,在本地安装 Swagger Codegen 工具。可以通过官方文档中的安装方法进行安装。 2. 创建一个 Swagger 规范文件,比如 `swagger.yaml`,内容如下: ``` swagger: '2.0' info: title: Example API version: '1.0.0' paths: /pets: get: summary: List all pets produces: - application/json responses: '200': description: OK schema: type: array items: type: object properties: id: type: integer format: int64 name: type: string ``` 这个 Swagger 规范文件定义了一个 `/pets` 路径,当使用 GET 方法请求该路径时,会返回一个包含所有宠物信息的 JSON 数组。 3. 使用 Swagger Codegen 生成 Python 代码。在终端中执行以下命令: ``` swagger-codegen generate -i swagger.yaml -l python -o ./petstore ``` 这个命令会使用 `swagger.yaml` 文件中的规范生成 Python 代码,并将代码输出到 `./petstore` 目录中。 4. 在 `./petstore` 目录中,可以看到生成Python 代码,包括 `README.md` 文件和 `swagger_client` 目录。 5. 在 Python 代码中,可以使用 `swagger_client` 包中的方法来调用 API。比如,要列出所有宠物信息,可以使用以下代码: ```python from swagger_client.api_client import ApiClient from swagger_client.pet_api import PetApi # 创建 API Client api_client = ApiClient() api_client.host = 'http://petstore.swagger.io/v2' # 创建 PetApi 实例 pet_api = PetApi(api_client) # 调用 list_pets 方法,列出所有宠物信息 pets = pet_api.list_pets() print(pets) ``` 这样,就可以使用 Swagger Codegen 生成Python 代码来调用 API 了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

RayCheungQT

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值