Getting int or float response from redis stream and python

2k views Asked by At

I am adding data to a redis stream with the data being integers or floats

> XADD name 1-0 field 1
> XADD name 1-1 field 2

I then have a python app that reads the stream data.

r = redis.Redis(host=HOST,port=PORT,decode_responses=True)

latest = r.xrevrange(
        name="name",
        count=1
    )

#[[
#  "1-1",
#  {
#    "field":"2"  ##data is str not int
#  }
#]]

The issue is that the resulting data in the dictionary will always be in string format. Someone suggested I use hiredis, but I cannot find how to get a non-string output. Is there a way that redis or hiredis can automatically cast the data to the proper numerical type? or do I have to implement the casting myself?

2

There are 2 answers

0
Bharel On BEST ANSWER

Redis is a textual/binary database. Inserting an int converts it to a string immediately upon entry.

You must convert the response back to int yourself. Decode response only decodes the bytes response to str.

0
Frank Yellin On

Alternatively use pickle before storing and after retrieving your objects.

r.set('some_key', pickle.dumps(obj)
obj = pickle.loads(r.get('some_key'))

As far as redis is concerned, it's storing and retrieving bytes.