[英]How to get rid of 500 Internal Server Error using Python and Flask?
I am getting an Internal Server Error on my website.我的网站出现内部服务器错误。 When you go to the results page it'll throw the 500 Internal Server Error.
当您将 go 转到结果页面时,它会抛出 500 Internal Server Error。 I am not really sure why.
我不太确定为什么。 It says I am getting a "KeyError: 'test'".
它说我收到“KeyError:'test'”。
Here is the code in Python:这是 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)
And here is the "KeyError:" I am getting:这是“KeyError:”我得到:
Here is some more code:这是更多代码:
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)
The problem according to your screenshot is that votes
does not have a key as the value of voted
.根据您的屏幕截图,问题是
votes
没有键作为voted
的值。 If you change votes
to be - votes=Counter()
or votes=defaultdict(int)
(both imported from collections that's should solve it)如果您将
votes
更改为 - votes=Counter()
或votes=defaultdict(int)
(都从 collections 导入,应该可以解决)
This is just a hunch without more information but I bet the problematic line is this这只是一个没有更多信息的预感,但我敢打赌有问题的线是这个
voted = line.rstrip("\n")
votes[voted] += 1
As written the votes dictionary is populated from a different dataset, poll_data, than the one used to accumulate votes, "file".正如所写,投票字典是从不同的数据集 poll_data 填充的,而不是用于累积投票的数据集“文件”。 If a key exists in "file" that does not exist in poll_data you would expect to see the error you've written.
如果在 poll_data 中不存在的“文件”中存在一个键,您可能会看到您编写的错误。
Based on this snippet you might benefit from the defaultdict in the collections module.基于此代码段,您可能会受益于 collections 模块中的 defaultdict。
Add添加
import collections
Replace代替
votes = {}
for f in poll_data['fields']:
votes[f] = 0
With和
votes = collections.defaultdict(int)
The default dictionary will allow you retrieve values where no key exists which is what your code does with the +=
operator.默认字典将允许您检索不存在键的值,这就是您的代码使用
+=
运算符所做的。 In the case the default dictionary defaults the key value to the int function output which is zero.在这种情况下,默认字典将键值默认为 int function output 这是零。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.