![](/img/trans.png)
[英]Deploying Python web app (Flask) in IIS using FastCGI get 500 Internal Server Error
[英]How to get rid of 500 Internal Server Error using Python and Flask?
我的网站出现内部服务器错误。 当您将 go 转到结果页面时,它会抛出 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)
这是更多代码:
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)
根据您的屏幕截图,问题是votes
没有键作为voted
的值。 如果您将votes
更改为 - votes=Counter()
或votes=defaultdict(int)
(都从 collections 导入,应该可以解决)
这只是一个没有更多信息的预感,但我敢打赌有问题的线是这个
voted = line.rstrip("\n")
votes[voted] += 1
正如所写,投票字典是从不同的数据集 poll_data 填充的,而不是用于累积投票的数据集“文件”。 如果在 poll_data 中不存在的“文件”中存在一个键,您可能会看到您编写的错误。
基于此代码段,您可能会受益于 collections 模块中的 defaultdict。
添加
import collections
代替
votes = {}
for f in poll_data['fields']:
votes[f] = 0
和
votes = collections.defaultdict(int)
默认字典将允许您检索不存在键的值,这就是您的代码使用+=
运算符所做的。 在这种情况下,默认字典将键值默认为 int function output 这是零。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.