如何将 Python3 请求中的数据传递给 VMware 工作站 api?

how to pass data in Python3 requests to VMware workstation api?

问题:

我正在尝试为我的虚拟机启动开机命令。我可以在 windows 命令行中这样做,curl 使用

传递有问题的数据
curl "http://127.0.0.1:8697/api/vms/vm_id/power" -X PUT --header "Content-Type: application/vnd.vmware.vmw.rest-v1+json" --header "Accept: application/vnd.vmware.vmw.rest-v1+json" --header "Authorization: Basic MyToken" -d on                                                                                       
{"power_state": "poweredOn}

我不太了解headers的概念和数据。我所知道的是我需要在 post 请求的 body 中插入操作“on”。我可怜我电脑上的 RAM,因为所有那些 chrome 选项卡都保持打开状态。看来我碰壁了。提前提供的任何帮助。

代码:

import requests
import json

api_token = MyToken
desired_vm_id = vm_id
headers = {'Accept': 'application/vnd.vmware.vmw.rest-v1+json','Authorization': 'Basic {0}'.format(api_token)}
api_url_base = 'http://127.0.0.1:8697/api/vms/'

def get_vm_status():
    api_url = '{0}{1}/power'.format(api_url_base, desired_vm_id)
    response = requests.get(api_url, headers=headers)
    if response.status_code == 200:
        response = json.loads(response.content)
        if (response['power_state']) == 'poweredOff':
          response_for_put = requests.put(api_url, headers = headers, data = {'operation': 'on'})
          result = json.loads(response_for_put.content)
          print(result['Message'])
        else:
          print('VM already running:', response)  
    else:
        return None        

get_vm_status()

结果:

Content type not supported

文档: from vmware workstation pro dockumentation

您似乎在 curl 命令中设置了 Content-Type header 而不是在 Python 代码中。尝试更改此行:

headers = {'Accept': 'application/vnd.vmware.vmw.rest-v1+json','Authorization': 'Basic {0}'.format(api_token)}

对此:

headers = {'Content-Type': 'application/vnd.vmware.vmw.rest-v1+json', 'Accept': 'application/vnd.vmware.vmw.rest-v1+json','Authorization': 'Basic {0}'.format(api_token)}

你可以试试这个:

response = requests.put(api_url, headers=headers, data='on')

然后您可以直接阅读JSON回复:

response.json()