【问题标题】:The debugger caught an exception in your WSGI application : Getting KeyError KeyError: 'main' Traceback (most recent call last)调试器在您的 WSGI 应用程序中捕获了一个异常:Getting KeyError KeyError: 'main' Traceback (most recent call last)
【发布时间】:2017-12-27 04:25:50
【问题描述】:

密钥错误

KeyError: '主要' Traceback(最近一次通话最后一次)

调试器在您的 WSGI 应用程序中发现了一个异常。您现在可以查看导致错误的回溯。

要在交互式回溯和纯文本回溯之间切换,您可以单击“回溯”标题。从文本回溯中,您还可以创建它的粘贴。对于代码执行,将鼠标悬停在要调试的框架上,然后单击右侧的控制台图标。

from flask import Flask, render_template, request
import requests

app = Flask(__name__)

@app.route('/temperature', methods=['POST'])
def temperature():
    zipcode = request.form['zip']
    r = requests.get('http://api.openweathermap.org/data/2.5/weather?zip='+zipcode+',us&appid=fd38d62aa4fe1a03d86eee91fcd69f6e')
    json_object = r.json()
    temp_k = float(json_object['main']['temp'])
    temp_f = (temp_k - 273.15) * 1.8 + 32
    return render_template('temperature.html', temp=temp_f)

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)

【问题讨论】:

  • 这就是你的全部代码吗?请您提供追溯。提示:您应该说出您尝试过的内容,并提供包括回溯在内的所有相关数据。这就是你被否决的原因。
  • 因此,与其复制所有告诉您如何获取回溯的文本,不如发布实际的回溯
  • 在尝试访问它们之前,请确保您的 json_object 中有正确的密钥。此外,它不检查 HTTP 错误。如果他们发送服务器错误会发生什么?
  • 在 requests.get 之前尝试 print(zipcode),看看你是否正确阅读。

标签: python json python-2.7 api


【解决方案1】:

阅读 API docs 看起来您的代码应该正确读取 JSON,因此您的 API 密钥不正确(您提供的密钥在我尝试时不是正确的,但您可能已对其进行了编辑)或 Zip您请求的代码不存在。

无论哪种方式,您都应该提供一个错误页面:

@app.route('/temperature', methods=['POST'])
def temperature():
    zipcode = request.form['zip']
    r = requests.get('http://api.openweathermap.org/data/2.5/weather?zip='+zipcode+',us&appid=fd38d62aa4fe1a03d86eee91fcd69f6e')
    json_object = r.json()
    try:
        temp_k = float(json_object['main']['temp'])
        temp_f = (temp_k - 273.15) * 1.8 + 32
        return render_template('temperature.html', temp=temp_f)
    except KeyError:
        msg = 'Unknown error'
        try:
            msg = json_object['message']
        except KeyError:
            pass

        print(msg)
        return render_template('temperature_error.html', error=msg)

它将提供服务器给出的错误消息,因此会指出问题所在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-13
    • 2022-12-07
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    相关资源
    最近更新 更多