Storing item views in Redis

Let's find a way to store the total number of times an image has been viewed. If we implement this using the Django ORM, it will involve an SQL UPDATE query every time an image is displayed. If we use Redis instead, we just need to increment a counter stored in memory, resulting in a much better performance and less overhead.

Edit the views.py file of the images application and add the following code to it after the existing import statements:

import redis
from django.conf import settings

# connect to redis
r = redis.StrictRedis(host=settings.REDIS_HOST,
port=settings.REDIS_PORT,
db=settings.REDIS_DB)

With the preceding code, we establish the Redis connection in order to use it in our views. Edit the image_detail view and make it look as follows:

def image_detail(request, id, slug):
image = get_object_or_404(Image, id=id, slug=slug)
# increment total image views by 1
total_views = r.incr('image:{}:views'.format(image.id))
return render(request,
'images/image/detail.html',
{'section': 'images',
'image': image,
'total_views': total_views})

In this view, we use the incr command that increments the value of a given key by 1. If the key doesn't exist, the incr command creates it previously. The incr() method returns the final value of the key after performing the operation. We store the value in the total_views variable and pass it in the template context. We build the Redis key using a notation, such as object-type:id:field (for example, image:33:id).

The convention for naming Redis keys is to use a colon sign as a separator for creating namespaced keys. By doing so, the key names are especially verbose and related keys share part of the same schema in their names.

Edit the images/image/detail.html template of the images application and add the following code to it, after the existing <span class="count"> element:

<span class="count">
{{ total_views }} view{{ total_views|pluralize }}
</span>

Now, open an image detail page in your browser and reload it several times. You will see that each time the view is processed, the total views displayed is incremented by 1. Take a look at the following example:

Great! You have successfully integrated Redis into your project to store item counts.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset