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. I am not really sure why. It says I am getting a "KeyError: 'test'".
Here is the code in 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:
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
. If you change votes
to be - votes=Counter()
or votes=defaultdict(int)
(both imported from collections that's should solve it)
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". If a key exists in "file" that does not exist in poll_data you would expect to see the error you've written.
Based on this snippet you might benefit from the defaultdict in the collections module.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.