我正在构建一个使用Python后端来处理API调用的React应用程序。当我试图访问API数据时,我只是不断得到错误。凭证(硬编码但已删除)经过双重检查并正确无误。我从来没有访问过需要身份验证/令牌的api,我现在有点卡住了。
from flask import Flask, jsonify
from flask_cors import CORS
import os
import requests
from xml.etree import ElementTree as ET
app = Flask(__name__)
CORS(app, resources={r'*': {'origins': '*'}})
# Your provided credentials
# Deleted for this question
# Test route that returns a simple string on the page
@app.route('/')
def hello():
return 'Hello World! This is the MaaS360 API Proxy.'
# Check the response status code and raise an exception if it's not 200
def check_response_status(response):
if response.status_code != 200:
raise Exception(
f"API call failed with status code {response.status_code}: {response.text}")
if response.status_code == 500:
error_message = response.json().get(
'authResponse', {}).get('errorDesc', 'Unknown error')
raise Exception(
f"API call failed with status code 500: {error_message}")
elif response.status_code != 200:
raise Exception(
f"API call failed with status code {response.status_code}: {response.text}")
# Fetches the data from the MaaS360 API
def fetch_maas360_data():
try:
auth_url = f'{api_base_url}/auth-apis/auth/1.0/authenticate/{billing_id}'
auth_data = f'''<authRequest>
<maaS360AdminAuth>
<billingID>{billing_id}</billingID>
<platformID>{platform_id}</platformID>
<appID>{app_id}</appID>
<appVersion>{app_version}</appVersion>
<appAccessKey>{app_access_key}</appAccessKey>
<userName>{username}</userName>
<password>{password}</password>
</maaS360AdminAuth>
</authRequest>'''
headers = {
'Content-Type': 'application/xml'
}
auth_r = requests.post(auth_url, headers=headers, data=auth_data)
check_response_status(auth_r)
auth_response_content = auth_r.content.decode('utf-8')
auth_token = ET.fromstring(
auth_response_content).find("authToken").text
headers = {
'Authorization': f'MaaS token "{auth_token}"',
'Content-Type': 'application/xml',
'x-maas360-tenant-id': billing_id
}
api_url = f'{root_ws_url}/deviceapis/devices/1.0/search/{billing_id}'
response = requests.get(api_url, headers=headers)
check_response_status(response)
devices_xml = ET.fromstring(response.content)
devices_list = []
for device in devices_xml.findall('device'):
device_name = device.find('deviceName').text
platform_name = device.find('platformName').text
maas360_device_id = device.find('maas360DeviceID').text
user_name = device.find('username').text # Changed variable name
last_reported = device.find('lastReported').text
device_status = device.find('deviceStatus').text
devices_list.append({
'id': maas360_device_id,
'name': device_name,
'os': platform_name,
'username': user_name, # Changed variable name
'lastReported': last_reported,
'deviceStatus': device_status
})
check_response_status(response)
return devices_list
except Exception as e:
print(f"Error fetching data from MaaS360 API: {e}")
return [{'error': f"Error fetching data from MaaS360 API: {e}"}]
# Route that returns the data from the MaaS360 API
@app.route('/api/maas360')
def maas360():
data = fetch_maas360_data()
if 'error' in data:
return jsonify(data), 500
else:
return jsonify(data)
# Run the Flask app. Debug mode is enabled so that the server will reload and the name is set to the name of the file
if __name__ == '__main__':
print("Starting Flask server...")
app.run(debug=True)
当我运行curl时,我得到这个:"Error ": "Error with MaaS360 API authentication:
HTTPSConnectionPool(host='services.m1.maas360.com', port=443): Max retries exceeded with url: /auth-apis/auth/1.0/authenticate/1180218 (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x103c303a0>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known'))"
我试过使用Postman,但是从来没有用过,并且在设置时遇到了问题。
我相信您可能在授权头中缺少一个等号。我是这样写的:
headers = {
"Authorization": f"MaaS token="{authorizationToken}
编辑:第二眼看,似乎你的错误发生在Auth阶段,在我引用的代码行甚至到达之前。
你的标题和正文看起来都是正确的,所以我唯一能想象的是你的URL有问题;基础URL应该是:https://services.fiberlink.com/...
你的错误信息提到了一些其他的URL,所以也许这就是问题所在。