我正在尝试使用python请求从api获取一些数据。我的代码如下:
response = settings.get_request_with_token(settings.api_url, settings.token)
dashboard = json.loads(response.decode("utf-8"))
get_request_with_token
如下:
def post_request_with_token(url, api_key, json_payload={}):
r = requests.post(url, headers={'Authorization': 'Bearer ' + api_key}, data=json_payload)
return r.content
在我的response
中,我得到以下结果:
'[{"id":1,"title":"Name","uri":"db/name","type":"dash-db","tags":[],"isStarred":false}]'
我使用json.loads
来获得以下结果:
[{u'tags': [], u'type': u'dash-db', u'title': u'Name', u'uri': u'db/name', u'isStarred': False, u'id': 1}]
但我无法摆脱'u'。
我尝试了.decode("utf-8")
,但我得到了同样的结果。
知道怎么解决吗?
更新
我正在尝试更新Grafana上的信息中心,我收到以下错误:
[{u'message': u"invalid character 'm' looking for beginning of value", u'classification': u'DeserializationError'}, {u'message': u'Required', u'classification': u'RequiredError', u'fieldNames': [u'Dashboard']}]
UDPDATE2
整个脚本如下所示:
try:
dashboard_name = sys.argv[1] # Get the argument
# Get dashboard from QA organisation (we give default api token. The default token is from QA organisation from grafana)
response = settings.get_request_with_token(settings.api_url + "search?query=" + dashboard_name, settings.token)
dashboard = json.loads(response.decode("utf-8"))
if len(dashboard) < 1:
print("There is no dashboard data.")
else:
dashboard_data = dashboard[0]
dashboard_uri = str(dashboard_data["uri"])
dashboard_details = dashboard_api.get_dashboard(dashboard_uri, settings.token)
# Get all organisations
all_organisations = organization_api.get_all_organizations() # Get all organisations
for org in all_organisations:
if org['id'] == 28:
org_data_list = filter(lambda organisation: organisation['grafana_id'] == org['id'], settings.organisations)
try:
current_org_api_key = org_data_list[0]['api_key']
result = dashboard_api.add_dashboard(current_org_api_key, dashboard_details["dashboard"])
print(result)
pdb.set_trace()
except:
pass
except IndexError:
print("Please provide dashboard name!")
函数get_request_with_token
如下所示:
def get_request_with_token(url, api_key):
r = requests.get(url, headers={'Authorization': 'Bearer ' + api_key})
return r.content
函数get_dashboard
如下所示:
def get_dashboard(board_uri, token):
response = settings.get_request_with_token(settings.api_url + "dashboards/{0}".format(board_uri), token)
return json.loads(response.encode("utf-8"))
函数add_dashboard
如下所示:
def add_dashboard(token, json_payload):
response = settings.post_request_with_token(settings.api_url + "dashboards/db", token, json_payload)
return json.loads(response)
函数post_request_with_token
如下所示:
def post_request_with_token(url, api_key, json_payload={}):
r = requests.post(url, headers={'Authorization': 'Bearer ' + api_key, 'Content-Type': 'application/json'}, data=json_payload)
return r.content