KeyError但Dict有效并包含正确的密钥

2024-05-20 01:32:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在运行一个小的Flask应用程序,它与Elasticsearch进行通信,并从ES返回的数据中显示一些格式化的统计信息。你知道吗

我有一个特殊的查询,它返回一个dict值。你知道吗

查询返回的数据:

{'took': 6, 'timed_out': False, '_shards': {'total': 72, 'successful': 72, 'skipped': 0, 'failed': 0}, 'hits': {'total': {'value': 84, 'relation': 'eq'}, 'max_score': None, 'hits': []}, 'aggregations': {'all_matching_docs': {'buckets': {'all': {'doc_count': 84, 'total_traffic': {'value': 10276020.0}, 'host_traffic_rate_bit_s': {'value': 0.27402719999999997}}}}}}

在一个独立的Python脚本中,我使用以下数据结构来访问“host\u traffic\u rate\u bit\s”的值。你知道吗

test = res_bucket_test['aggregations']['all_matching_docs']['buckets']['all']['host_traffic_rate_bit_s']['value']
print(test)
0.27402719999999997

它工作并显示正确的值。你知道吗

我在Flask应用程序中使用了完全相同的逻辑,但是我必须在try/except中包装相同的结构。如果我没有,我会得到以下错误

total_mbit_s = res_mbit_s['aggregations']['all_matching_docs']['buckets']['all']['host_traffic_rate_bit_s']['value']
KeyError: 'host_traffic_rate_bit_s'

使用try/except结构。你知道吗

try:
  total_mbit_s = res_mbit_s['aggregations']['all_matching_docs']['buckets']['all']['host_traffic_rate_bit_s']['value']
except:
  total_mbit_s = 'potato'

请注意,“potato”值从未分配给变量。最终结果仍然是value变量中包含的值。你知道吗

我得到了烧瓶显示的正确值。你知道吗

我知道数据被正确解析并发送到Flask,就好像我只显示res_mbit_s['aggregations']['all_matching_docs']['buckets']['all'],我得到{'doc_count': 121, 'total_traffic': {'value': 147044.0}, 'host_traffic_rate_bit_s': {'value': 0.003921173333333333}},这意味着我应该能够访问Dict的“host\u traffic\u rate\u bit\s”键

我不确定代码在哪里会失败。唯一的“真正”区别是在调用URL时独立运行.py或在Flask应用程序本身中运行。你知道吗

如果你需要更多的细节请告诉我!你知道吗


Tags: 应用程序hostflaskdocsratevaluebitres
1条回答
网友
1楼 · 发布于 2024-05-20 01:32:52

所以我从零开始,意识到一个关键的区别是请求的来源。我正在使用源IP查找来自ES的相关流量,如果源IP没有任何流量登录到ES,则似乎不会返回密钥。你知道吗

  1. 如果请求来自ES已知的IP,则返回数据并 dict密钥有效。你知道吗
  2. 如果请求来自没有任何日志的IP,则dict将被截断,并且该值不存在,这就是出现KeyError的原因。你知道吗
try:
  total_mbit_s = res_mbit_s['aggregations']['all_matching_docs']['buckets']['all']['host_traffic_rate_bit_s']['value']
except KeyError:
  total_mbit_s = 0

相关问题 更多 >