0

I come from Java background and most of my thinking comes from there. Recently started learning Python. I have a case where I want to just create one connection to Redis and use it everywhere in the project. Here is how my structure and code looks.

module: state.domain_objects.py

    class MyRedis():    
    global redis_instance
    def __init__(self):
        redis_instance = redis.Redis(host='localhost', port=6379, db=0)
        print("Redus instance created", redis_instance)

    @staticmethod
    def get_instance():
        return redis_instance

    def save_to_redis(self, key, object_to_cache):
        pickleObj = pickle.dumps(object_to_cache)
        redis_instance.set(key, pickleObj)

    def get_from_redis(self, key):
        pickled_obj = redis_instance.get(key)
        return pickle.loads(pickled_obj)

    class ABC():
        ....

Now I want to use this from other modules.

module service.some_module.py

from state.domain_objects import MyRedis
from flask import Flask, request

@app.route('/chat/v1/', methods=['GET'])
def chat_service():
    userid = request.args.get('id')
    message_string = request.args.get('message')
    message = Message(message_string, datetime.datetime.now())

    r = MyRedis.get_instance()
    user = r.get(userid)


if __name__ == '__main__':
    global redis_instance
    MyRedis()
    app.run()

When I start the server, MyRedis() __init__ method gets called and the instance gets created which I have declared as global. Still when the service tries to access it when the service is called, it says NameError: name 'redis_instance' is not defined I am sure this is because I am trying to java-fy the approach but not sure how exactly to achieve it. I read about globals and my understanding of it is, it acts like single variable to the module and thus the way I have tried doing it. Please help me clear my confusion. Thanks!

Nullman
  • 4,179
  • 2
  • 14
  • 30
rishi
  • 2,564
  • 6
  • 25
  • 47
  • 1
    `global` in python doesn't mean what you think it means. it lets you overwrite variables that are defined outside the current scope. [here is an explenation](https://stackoverflow.com/questions/4693120/use-of-global-keyword-in-python) – Nullman Aug 09 '17 at 13:44
  • 3
    The `global redis_instance` needs to be inside of `__init__()` for it to have any effect - it's currently a local variable at the point where you assign to it. And the `global redis_instance` in your main module does nothing - the name doesn't exist at all in the context of that module. – jasonharper Aug 09 '17 at 13:44
  • 2
    since you are using flask, you should probably use its own global variable mechanics specifically ["g"](http://flask.pocoo.org/docs/0.10/api/#flask.g) – Nullman Aug 09 '17 at 13:47
  • @jasonharper can you put it as answer so that I can accept it? – rishi Aug 09 '17 at 13:50

0 Answers0