【英文】Django项目中连接Redis

Preface

Learn notes on Redis connection in Django projects

Download dependencies

1
2
pip3 install redis
pip3 install django-redis

Modify global configuration

  • Add CACHES configuration after DATABASES configuration in the global configuration

CLIENT_CLASS: specify the client
CONNECTION_POOL_KWARGS: specify the connection pool configuration

max_connections: specify the maximum number of connections

PASSWORD: specify the password, leave it blank if there is none

//settings.py
1
2
3
4
5
6
7
8
9
10
11
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://127.0.0.1:6379',
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
'CONNECTION_POOL_KWARGS': {'max_connections': 200},
#'PASSWORD': ''
}
}
}

Redis decorator as MySQL cache

  • When querying data from MySQL, first query from Redis
    • If the data is available in Redis, retrieve it directly from Redis
    • If the data is not available in Redis, query it from MySQL and store it in Redis
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import json
from functools import wraps
from django_redis import get_redis_connection
from django.db import models

# Define a cache decorator
_cache = get_redis_connection('default')
def cache(func):
@wraps(func)
def wrapper(obj, *args):
key = args[0]
value = _cache.get(key)
if value:
return json.loads(value)
result = func(obj, *args)
_cache.set(key, json.dumps(result))
return result
return wrapper

class User(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=5)

# Define a class method `get()` using the cache decorator. When data needs to be retrieved from the cache, simply call `get()` method
@classmethod
@cache
def get(cls, id):
# Query data from MySQL and save it to Redis
result = cls.objects.get(id=id)
return {
'id': result.id,
'name': result.name
# If there is a date-time type data, it needs to be converted to string
#'time': str(result.time)
}

CRUD operations

Import modules

1
from django_redis import get_redis_connection

Get connection

1
cache = get_redis_connection('default')

Add or modify

Without specifying expiration time

1
cache.set('<key>', '<value>')

Specify expiration time

<num>: specify the expiration time in seconds

1
cache.set('<key>', '<value>', <num>)

Done

References

Bilibili - Turing Academy Tutorial