I believe everyone is familiar with Django's redis Cache server. like memcached, it is a high-performance key-value database. what is a cache server, du Niang has a very clear introduction. I will not introduce them here.
Under what circumstances will we use the cache server? This is not required in all situations. Generally, you need to put this field on the cache server only when you need to read a field frequently, in addition, the key-value database generally only stores simple data. Therefore, you must select an object to be saved.
Next I will introduce how to configure and use the redis database in Django. first, install redis and execute the following command in Ubuntu:
# Install the Redis server
sudo apt-get install redis-server
To use redis in Django, you also need to install the redis for Django plug-in:
pip install django-redis
This is an open-source project. the github address is https://github.com/niwibe/django-redis. thank you.
Now it is configured in settings of Django.
CACHES = { 'default': { 'BACKEND': 'redis_cache.cache.RedisCache', 'LOCATION': '127.0.0.1:6379', "OPTIONS": { "CLIENT_CLASS": "redis_cache.client.DefaultClient", }, },}REDIS_TIMEOUT=7*24*60*60CUBES_REDIS_TIMEOUT=60*60NEVER_REDIS_TIMEOUT=365*24*60*60
In fact, only those in CACHES can be used. the following three sentences are not required, but I need to use them in the following example. I will configure them here.
Now that the connection and configuration have been completed, how can we use them in the project? Next, let's take a look at the example below.
from django.conf import settingsfrom django.core.cache import cache#read cache user iddef read_from_cache(self, user_name): key = 'user_id_of_'+user_name value = cache.get(key) if value == None: data = None else: data = json.loads(value) return data#write cache user iddef write_to_cache(self, user_name): key = 'user_id_of_'+user_name cache.set(key, json.dumps(user_name), settings.NEVER_REDIS_TIMEOUT)
The above two methods can be used to read redis. you only need to pass the required field as a parameter to the method.
What about memcached? The configuration is the same:
CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', }}
Of course, its usage is the same as that in my previous example. In fact, for cache servers such as redis, the configuration is very simple, and the specific use is not difficult. There are many simple and clear examples on the official website for our reference, there is only one thing to note, that is, what kind of information should be stored in redis is what we really need to care about.