debugging 如何在访问对象的值时修复KeyError?

5tmbdcev  于 2022-11-14  发布在  其他
关注(0)|答案(1)|浏览(137)

我正在尝试创建一个应用程序,让你搜索一家公司的股票缩写,并返回所有必要的数据在Tkinter。我发现了一个很好的API,但当从API获取数据,它返回一个KeyError。请帮助调试这个。
我的代码:

import http.client as client
from tkinter import *
import json

root = Tk()
root.geometry('500x500')
conn = client.HTTPSConnection("realstonks.p.rapidapi.com")

headers = {
    'X-RapidAPI-Key': "6ce88770d0mshaf38a1d3b2c09b4p1a3d14jsn3c3ba4f28d50",
    'X-RapidAPI-Host': "realstonks.p.rapidapi.com"
    }
inputbox = Text(root, padx = 40, pady = 30).pack()
name = ""
def search_function():
  name = inputbox.get("1.0","end-1c")
search = Button(root, text = "Search Info", background = "gray", command = search_function)
conn.request("GET", "/" + name.upper(), headers=headers)

res = conn.getresponse()
data = res.read()

data_obj = json.loads(data.decode('utf-8'))
vol = data_obj['total_vol']
price = data_obj['price']
percent = data_obj['change_percentage']
if percent < 0:
    fg = 'red'
elif percent > 0:
    fg = 'green'
elif percent == 0:
    fg = 'gray'
title_widget = Label(root, text = name, font = ("arial bold", 50), underline = True).pack()
vol_widget = Label(root, text = vol + " in total.", font = ("arial bold", 40)).pack()
price_widget = Label(root, text = str(price) + " dollars per share.", font = ("arial bold", 30)).pack()
percent_widget = Label(root, text = str(percent) + "%", font = ("arial bold", 20), fg = fg).pack()
root.mainloop()

错误

Traceback (most recent call last):
  File "main.py", line 24, in <module>
    vol = data_obj['total_vol']
KeyError: 'total_vol'
tf7tbtn2

tf7tbtn21#

在解决问题后,请注意更改api。

import http.client

conn = http.client.HTTPSConnection("realstonks.p.rapidapi.com")

headers = {
    'X-RapidAPI-Key': "6ce88770d0mshaf38a1d3b2c09b4p1a3d14jsn3c3ba4f28d50",
    'X-RapidAPI-Host': "realstonks.p.rapidapi.com"
    }

conn.request("GET", "/TSLA", headers=headers)

res = conn.getresponse()
data = res.read()

print(data.decode("utf-8"))

{"price": 885.25, "change_point": -4.75, "change_percentage": -0.53, "total_vol": "20.47M"} #This is the Output

要保留需要转换为json的值,所以:

import json
result = data.decode("utf-8")
result_data = json.loads(result)

price = result_data["price"]
change_point = result_data["change_point"]
change_percentage = result_data["change_percentage"]
total_vol = result_data["total_vol"]

相关问题