如何让 Swagger 生成的 Python 客户端工作?

How do I get the Swagger-generated Python client to work?

我已经从 https://editor.swagger.io/ 生成了 python 客户端和服务器 - 服务器在没有编辑的情况下正确运行,但我似乎无法让客户端与其通信 - 或者与任何东西。

我怀疑我在做一些非常愚蠢的事情,但我在 Internet 上找到的示例要么不起作用,要么似乎期望我了解如何制作该对象。这是我的代码(我也尝试过不发送任何内容、字符串等):

import time
import swagger_client
import json
from swagger_client.rest import ApiException
from pprint import pprint

# Configure OAuth2 access token for authorization: petstore_auth
swagger_client.configuration.access_token = 'special-key'
# create an instance of the API class
api_instance = swagger_client.PetApi()
d = '{"id": 0,"category": {"id": 0,"name": "string"},"name": "doggie","photoUrls": ["string"],  "tags": [ {      "id": 0,      "name": "string"    }  ],  "status": "available"}'
python_d = json.loads(d)
print( json.dumps(python_d, sort_keys=True, indent=4) )
body = swagger_client.Pet(python_d) # Pet | Pet object that needs to be added to the store

try:
    # Add a new pet to the store
    api_instance.add_pet(body)
except ApiException as e:
    print("Exception when calling PetApi->add_pet: %s\n" % e)

我正在使用 python 3.6.4,当上述运行时我得到:

Traceback (most recent call last):
  File "petstore.py", line 14, in <module>
    body = swagger_client.Pet(python_d) # Pet | Pet object that needs to be added to the store
  File "/Users/bombcar/mef/petstore/python-client/swagger_client/models/pet.py", line 69, in __init__
    self.name = name
  File "/Users/bombcar/mef/petstore/python-client/swagger_client/models/pet.py", line 137, in name
    raise ValueError("Invalid value for `name`, must not be `None`")  # noqa: E501
ValueError: Invalid value for `name`, must not be `None`

我觉得我犯了一个非常基本的错误,但我确实从 https://editor.swagger.io/ 中复制了 JSON - 但由于我找不到实际工作的示例,所以我没有知道我错过了什么。

Python 客户端生成器为 API 生成 object-oriented 包装器。您不能直接 post 字典或 JSON 字符串,您需要使用生成的包装器创建一个 Pet 对象:

api_instance = swagger_client.PetApi()
pet = swagger_client.Pet(name="doggie", status="available",
                         photo_urls=["http://img.example.com/doggie.png"],
                         category=swagger_client.Category(id=42))

response = api_instance.add_pet(pet)

我最近遇到了类似的问题,最后通过在本地升级 python 版本解决了这个问题。我从 https://editor.swagger.io/ 生成了 python-flask-server zip 文件。然后我在本地用py 3.6.10搭建环境。使用“Model_Name.from_dict()”解析输入时出现同样的错误,告诉我

raise ValueError("Invalid value for `name`, must not be `None`")  # noqa: E501 
ValueError: Invalid value for `name`, must not be `None`

然后升级到python3.7.x,问题解决了。我知道你的问题与版本无关,但是,以防万一有人遇到类似问题并寻求帮助可以看到这个答案。