我已经从 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 生成面向对象的包装器。您不能直接发布字典或 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)
