2

I am using redis to try to save a request's session object. Based on how to store a complex object in redis (using redis-py), I have:

def get_object_redis(key,r):
    saved = r.get(key)
    obj = pickle.loads(saved)
    return obj

redis = Redis()
s = get_object_redis('saved',redis)

I have situations where there is no saved session and 'saved' evaluates to None. In this case I get:

TypeError: must be string or buffer, not None

Whats the best way to deal with this?

Community
  • 1
  • 1
user1592380
  • 34,265
  • 92
  • 284
  • 515

1 Answers1

2

There are several ways to deal with it. This is what they would have in common:

def get_object_redis(key,r):
    saved = r.get(key)
    if saved is None:
        # maybe add code here
        return ... # return something you expect
    obj = pickle.loads(saved)
    return obj

You need to make it clear what you expect if a key is not found.

Version 1
An example would be you just return None:

def get_object_redis(key,r):
    saved = r.get(key)
    if saved is None:
        return None
    obj = pickle.loads(saved)
    return obj

redis = Redis()
s = get_object_redis('saved',redis)

s is then None. This may be bad because you need to handle that somewhere and you do not know whether it was not found or it was found and really None.

Version 2
You create an object, maybe based on the key, that you can construct because you know what lies behind a key.

class KeyWasNotFound(object):
    # just an example class
    # maybe you have something useful in mind
    def __init__(self, key):
        self.key = key

def get_object_redis(key,r):
    saved = r.get(key)
    if saved is None:
        return KeyWasNotFound(key)
    obj = pickle.loads(saved)
    return obj

Usually, if identity is important, you would store the object after you created it, to return the same object for the key.

Version 3
TypeError is a very geneneric error. You can create your own error class. This would be the preferred way for me, because I do not like version 1 and do not have knowledge of which object would be useful to return.

class NoRedisObjectFoundForKey(KeyError):
    pass

def get_object_redis(key,r):
    saved = r.get(key)
    if saved is None:
        raise NoRedisObjectFoundForKey(key)
    obj = pickle.loads(saved)
    return obj
User
  • 14,131
  • 2
  • 40
  • 59
  • 1
    Consider to post the addendum as a new question. Otherwise much fewer people will read it. It is a totally different question. @user61629 – User Jul 06 '15 at 19:13
  • a follow up question is at http://stackoverflow.com/questions/31254837/python-pickle-indexerror-list-index-out-of-range – user1592380 Jul 06 '15 at 20:18