Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use redis commands for lists and sets in Django app

I am working on a Django app where I want to use redis for cache purpose.

I see that there are few packages like django-redis and django-redis-cache which integrates with Django and one can use to access redis.

But, with those packages you only have 'get' and 'set' commands to use.

How to use other redis commands for lists,sets, sorted sets like rpush, lrange, zadd?

Can we use it with the above mentioned packages (django-redis, django-redis-cache) or we need to use redis-py client?

Thanks for your help!

like image 784
raghvendra Avatar asked Dec 19 '22 16:12

raghvendra


2 Answers

You can access the raw redis connection in django-redis. I believe this allows you to execute commands via redis-py which it uses under the hood.

like image 186
Aaron Avatar answered Dec 22 '22 11:12

Aaron


Using of Raw client access :

In some situations your application requires access to a raw Redis client to use some advanced features that aren’t exposed by the Django cache interface.

>>> from django_redis import get_redis_connection
>>> con = get_redis_connection("default")

Now we can execute raw commands of Redis data type :

  1. List
  2. Sets
  3. Sorted Sets
  4. Hash etc

Example :

Storing data into Redis hash.

Redis Hashes are maps between string fields and string values, so they are the perfect data type to represent objects.

# Create framework dictionary in python
>>> frameworks = {'python':'Django','php':'Laravel','java':'Spring'} 
#Store them into redis hash.  
>>> con.hmset('frameworks',frameworks)
True #successfully stored 

# retrieved number of items 
>>> con.hlen('frameworks') 
3

#Get all values
>>> con.hvals('frameworks')
[b'Django', b'Laravel', b'Spring']

Hash commands used in above example :

  1. hmset : Set multiple items

  2. hlen : Get number of items

  3. hvals : return all values

like image 38
Muhammad Faizan Fareed Avatar answered Dec 22 '22 12:12

Muhammad Faizan Fareed