Json dictionnary on Redis - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Json dictionnary on Redis (/thread-14511.html) |
Json dictionnary on Redis - katsu707 - Dec-04-2018 Hi everyone, I'm a complete beginner and here's my issue: I have Flask as a webserver, Redis is counting the number of hits on the root. I added a arg "name". I want to store and return a different count that I wish to link to the "name" var. I got some help and they advised to use a JSON dictionnary. I'm struggling with the implementation. My code looks like this: from flask import Flask from redis import Redis import json app = Flask(__name__) redis = Redis(host='redis', port=6379) @app.route('/') @app.route('/<name>') def hello(name): counts = json.loads(redis.get('hits'),('{}')) try: counts[name] += 1 except KeyError: counts[name] = 1 redis.set('hits', json.dumps(counts)) return 'Hello {} I have been seen {} times.\n'.format(name,counts[name]) if __name__ == "__main__": app.run(host="0.0.0.0", port=8000, debug=True)I keep getting this error and I don't know why... Thanks a lot!K. RE: Json dictionnary on Redis - DeaD_EyE - Dec-04-2018 The function json.loads takes 1 positional argument but 2 were given.The error message is very helpful. In line number 13, you should change the code from: counts = json.loads(redis.get('hits'),('{}'))to counts = json.loads(redis.get('hits'))When your intention was to have a default argument, if the key does not exist in redis (returns None), you can use following trick: counts = json.loads(redis.get('hits')) or {'hits': 0, 'something-else': 'foo'}First the key 'hits' is returned by redis. If this key is None the dict on the right side is assigned to the name counts. The first object, which evaluates to True is taken.0 , 0.0 , (0.0+0j) , False , None , empty: bytes , bytearray , list , tuple , dict , set evaluates to False .bool(None) == False bool({}) == False bool([]) == FalseYou can use this knowledge for default values: def hello(greeting=''): ''' print greeting on the screen if greeting is empty, Hello World is printed ''' text = greeting or 'Hello World' print(text) |