OVH Python API:创建实例不喜欢我的JSON?

OVH Python API: Creating an instance doesn’t like my JSON?

我正在尝试使用 python-ovh 来简单地创建一个实例,但这给我带来了麻烦。 API 文档实际上似乎给出了无效的 Python 代码(至少对于 Python3…),我不确定我做错了什么。我相信我通过了正确的 JSON 但 API 不喜欢它。我也很难通过搜索找到示例代码。

我的代码:

    self.inst = {}
    self.inst['flavorId'] = self.flavorid
    self.inst['imageId'] = self.imageid
    self.inst['name'] = self.name
    self.inst['region'] = self.region
    self.inst['monthlyBilling'] = False

    try:
        self.instance = client.post("/cloud/project/" + self.servicename + "/instance",
            json.dumps(self.inst, separators=(",",":"))
        )
    except ovh.APIError as e:
        print("JSON: " + json.dumps(self.inst, separators=(",",":")))
        print("Ooops, failed to create instance:", e)

调试输出:

JSON: {“flavorId”:“14c5fa3f-fdad-45c4-9cd1-14dd99c341ee”,“imageId”:“92bee304-a24f-4db5-9896-864da799f905”,“name”:“ovhcloud-test-1”,“region”:“BHS5”,“monthlyBilling”:false}

错误输出:

Ooops, failed to create instance: Missing parameter(s): flavorId, name, region \nOVH-Query-ID: CA.ext-3.6101d265.2209.d74765fb-6227-4105-a24b-c46c74f3e508\n"

API 文档告诉我这样做:

result = client.post(’/cloud/project/xxxxxx/instance’,
=’{“flavorId”:“14c5fa3f-fdad-45c4-9cd1-14dd99c34”,“imageId”:“92bee304-a24f-4db5-9896-864da799f905”,“monthlyBilling”:false,“name”:“testinstance”,“region”:“BHS5”,“userData”:“testdata”}’, // Request Body (type: cloud.ProjectInstanceCreation)
)

但这会导致语法错误,并且也不适用于变量替换。

谁能帮我告诉我哪里做错了?

client.post()参数中,您必须明确给出每个参数。 Python 客户端已经成功转换为 JSON,因此您不必自己管理 json.dumps()

下面是一个通过 Python 客户端调用 OVH API 来创建云实例的工作示例:

#!/usr/bin/env python
import ovh

client = ovh.Client(
    endpoint='ovh-eu',
    application_key='my_app_key',
    application_secret='my_secret_key',
    consumer_key='my_consumer_key'
)

project_id = 'my_cloud_project_id'    

try:
    instance = client.post(
        '/cloud/project/' + project_id + '/instance',
        flavorId='d145323c-2fe7-4084-98d8-f65c54bbbaf4',
        name='my_instance_name',
        region='GRA5',
        imageId='a125424e-3d5c-4276-a8ad-adf852ce1771',
        monthlyBilling=False
    )
except ovh.APIError as e:
    print('ERROR: ')
    print(e)

如果你想给一个 Python 字典作为参数(正如你在你的例子中尝试的那样),可以这样:

instance_creation_params = {
    'flavorId': 'd145323c-2fe7-4084-98d8-f65c54bbbaf4',
    'name': 'my_instance_name',
    'region':'GRA5',
    'imageId': 'a125424e-3d5c-4276-a8ad-adf852ce1771',
    'monthlyBilling': False    
}

try:
    instance = client.post(
        '/cloud/project/' + project_id + '/instance',
        **instance_creation_params
    )
except ovh.APIError as e:
    print('ERROR: ')
    print(e)