首页 > 解决方案 > 如何使用 Python 和 Flask 摆脱 500 内部服务器错误?

问题描述

我的网站出现内部服务器错误。当您转到结果页面时,它会抛出 500 Internal Server Error。我不太确定为什么。它说我收到“KeyError:'test'”。

这是Python中的代码:

 @app.route('/results/')
def results():
    votes = {}
    for f in poll_data['fields']:
        votes[f] = 0

    f  = open(file, 'r+')
    for line in f:
        voted = line.rstrip("\n")
        votes[voted] += 1
        

    return render_template('results.html', data=poll_data, votes=votes)

这是“KeyError:”我得到: 在此处输入图像描述

这是更多代码:

file = 'data0.txt'

 
@app.route('/')
def home():
    return render_template('home.html', data = poll_data)

@app.route('/poll')
def poll():
    vote = request.args.get('field')

    out = open(file, 'a+')
    out.write( vote + '\n' )
    out.close() 

    return render_template('thankyou.html', data = poll_data)

@app.route('/results/')
def results():
    votes = collections.defaultdict(int)
    for f in poll_data['fields']:
        votes[f] = 0

    f  = open(file, 'r+')
    for line in f:
        vote = line.rstrip("\n")
        votes[vote] += 1
        

    return render_template('results.html', data=poll_data, votes=votes)

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

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



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

标签: pythonhtmlcssflask

解决方案


根据您的屏幕截图,问题是votes没有键作为voted. 如果您更改votes为 -votes=Counter()votes=defaultdict(int)(都从应该解决的集合中导入)


推荐阅读