Python 调用 rest api 从 url 获取数据

Python call rest api to get data from url

我创建了一个 Bash 脚本来使用 rest APIusernamepassword 和保存的设备中获取 url 的数据Session ID 到变量中,然后使用会话 ID 将数据转换为工作正常的 csv 格式。

我想将 bash 代码更改为 python3 代码,因为我正在使用 pandas.

解析它

Bash代码:

#!/bin/bash

sessionID=$(curl -k -H "accept: application/json" -H "content-type: application/json" -H "x-api-version: 120" -d '{"userName":"administrator","password":"adminpass"}' -X POST https://hpe.sysnergy.com/rest/login-sessions | jq -r ".sessionID")


curl -k -H 'accept: application/json' \
        -H 'content-type: text/csv' \
        -H 'x-api-version: 2' \
        -H "auth: $sessionID" \
        -X GET https://hpe.sysnergy.com/rest/resource-alerts

Python 尝试代码版本:

#!/usr/bin/python3
import requests
import json

url = "https://hpe.sysnergy.com/rest/login-sessions"
data = {'username': 'administrator', 'password': 'adminpass'}
headers = {'Content-type': 'text/csv', 'Accept': 'application/json', 'x-api-version': 2}
r = requests.post(url, data=json.dumps(data), headers=headers)
print(r)

我遇到以下错误:

错误:

requests.exceptions.InvalidHeader: Value for header {x-api-version: 2} must be of type str or bytes, not <class 'int'>

如果我将 int 转换为 str 作为 '2' 那么它会给出另一个 ssl 错误:

requests.exceptions.SSLError: HTTPSConnectionPool(host='hpe.synerg.com', port=443): Max retries exceeded with url: /rest/login-sessions (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:877)'),))

编辑:

我尝试了一些不同的方法来获得与 python 中的 bash 相同的代码格式,但现在 returns 新响应代码出现新错误。

import os
import requests

sessionID = os.getenv('sessionID')

headers = {
    'accept': 'application/json',
    'content-type': 'text/csv',
    'x-api-version': '2',
    'auth': f"{sessionID}",
}

data = '{"userName":"administrator","password":"adminpassword"}'

response = requests.post('https://hpe.synergy.com/rest/login-sessions', headers=headers, data=data, verify=False)
print(response)

错误:

/python3/lib64/python3.6/site-packages/urllib3/connectionpool.py:1020: InsecureRequestWarning: Unverified HTTPS request is being made to host 'hpe.synergy.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning,

<Response [415]>

请帮助或建议在 python.

中实现相同功能的方法

您首先需要发出 POST 请求以获取 sessionID,然后您需要发出 GET 请求。另请注意,headers 对于 2 个请求略有不同。这样的事情应该有效:

import requests

session = requests.Session()

url = "https://hpe.sysnergy.com/rest/login-sessions"
credentials = {"userName": "administrator", "password": "adminpass"}
headers = {"accept": "application/json", 
           "content-type": "application/json", 
           "x-api-version": "120", 
          }

response = session.post(url, headers=headers, json=credentials, verify=False)

session_id = response.json()["sessionID"]

url = "https://hpe.sysnergy.com/rest/resource-alerts"
headers = {"accept": "application/json", 
           "content-type": "text/csv", 
           "x-api-version": "2", 
           "auth": session_id, 
          }

response = session.get(url, headers=headers, verify=False)

print(response)
#print(response.content) # returns bytes
#print(response.text) # returns string