[英]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.