Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tuple in redis / python: can store, not retrieve

Tags:

python

redis

So, I've got redis working with python -- exciting!

I need to store a tuple and retrieve it / parse it later. Construct below isn't working, I think because the returned tuple is quoted -- there is a quote on either end of it.

It seems to me that the quotes indicate that it isn't actually a tuple, but rather a string.

So does anyone know how to get redis to actually return a working tuple? Thanks!

>>> tup1 = ('2011-04-05', 25.2390232323, 0.32093240923490, 25.239502352390)
>>> r.lpush('9999', tup1)
1L
>>> r.lpop('9999')
"('2011-04-05', 25.2390232323, 0.3209324092349, 25.23950235239)"
>>> v = r.lpop('9999')
>>> test=v[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object has no attribute '__getitem__'
like image 522
Todd Curry Avatar asked Dec 09 '22 15:12

Todd Curry


2 Answers

If you would like to get the tuple back as such, I recommend using 'pickle'.

>>> tup1 = ('2011-04-05', 25.2390232323, 0.32093240923490, 25.239502352390)
>>> import pickle
>>> r.lpush('9999', pickle.dumps(tup1))
1L
>>> v = pickle.loads(r.lpop('9999'))
>>> v
('2011-04-05', 25.2390232323, 0.3209324092349, 25.23950235239)
>>> type(v)
<type 'tuple'>
>>> 
like image 191
harisibrahimkv Avatar answered Dec 11 '22 05:12

harisibrahimkv


I would go with karthikr's solution, but literal_eval from the standard lib is usually recommended as the safe alternative, as eval can execute arbitrary code if you give it funny input

>>> tup1 = "print('Dont use eval! ' * 2)"
>>> r.lpush('9999', tup1)
>>> v = r.lpop('9999')
>>> test = eval(v)
Dont use eval! Dont use eval!

literal_eval will create your tuple (or list or dict), but won't run functions.

>>> from ast import literal_eval
>>> tup1 = ('2011-04-05', 25.2390232323, 0.32093240923490, 25.239502352390)
>>> tup2 = "print('Dont use eval! ' * 2)"
>>> r.lpush('9999', tup2, tup1)
>>> v1 = r.lpop('9999')
>>> print(literal_eval(v1) == tup1)
True

>>> literal_eval(r.lpop('9999'))  # ==> SyntaxError: invalid syntax
like image 38
beardc Avatar answered Dec 11 '22 06:12

beardc