ARI FISHER
ARI FISHER

Reputation: 353

Why is there a KeyError when the dictionary has the key?

I am creating a simple flask application to store JSON files and read them. The application should return a JSON file I made as a test. Here's the url: http://IP:5000/?room=test&game=test. I got this error:

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/flask/app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/lib/python3/dist-packages/flask/app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/lib/python3/dist-packages/flask/app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/lib/python3/dist-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/usr/lib/python3/dist-packages/flask/app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/lib/python3/dist-packages/flask/app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/pi/Desktop/python/universalgameserver.py", line 10, in api_set
    return json.loads(readJSON(request.args['room'], request.args['game']))
  File "/home/pi/Desktop/python/universalgameserver.py", line 17, in readJSON
    f = open("~/saves/${room}_${game}.json".format(room, game), "r")
KeyError: 'room'

Printing out the dictionary, it looks like this:
{'room': 'test', 'game': 'test'}
My code looks like this:

from flask import Flask, request
import json
app = Flask(__name__)
@app.route("/", methods=["GET", "POST"])
def api_set():
    if request.method == "POST":
        writeJSON(request.form['room'], request.form['game'], request.form['json'])
    else:
        print(dict(request.args))
        return json.loads(readJSON(request.args['room'], request.args['game']))

def writeJSON(room, game, json):
    f = open("~/saves/${room}_${game}.json".format(room, game), "w")
    f.write(json)
    f.close()
def readJSON(room, game):
    f = open("~/saves/${room}_${game}.json".format(room, game), "r")
    contents = f.read()
    f.close()
    return contents
if __name__ == '__main__':
    app.run(host='192.168.0.36')

Upvotes: 2

Views: 458

Answers (1)

Aviv Yaniv
Aviv Yaniv

Reputation: 6298

The KeyError is raised in readJSON during the formatting of:

f = open("~/saves/${room}_${game}.json".format(room, game), "r")

Change it to:

If in Python 2:

f = open("~/saves/{0}_{1}.json".format(room, game), "r")

If in Python 3.6 or newer, using f-string which allows you to easy format:

f = open(f"~/saves/{room}_{game}.json", "r")

And it shall work like magic!

P.S.

Similarly, change in the writeJSON too.

Upvotes: 3

Related Questions