项目作者: Alexmhack

项目描述 :
Using redis and django-redis to perform caching for the django application
高级语言: Python
项目地址: git://github.com/Alexmhack/Django-Cache.git
创建时间: 2018-10-17T03:13:15Z
项目社区:https://github.com/Alexmhack/Django-Cache

开源协议:

下载


Django-Cache

Using redis and django-redis to perform caching for the django application

In this tutorial we will be setting up Redis and [Django] using [django-redis] and
enable caching for our django web application.

Caching refers to storing the server response in the client itself, so that a client need
not make a server request for the same resource again and again. A server response should
have information about how caching is to be done, so that a client caches the response
for a time period or never caches the server response.

Installation

First of all install Redis from the official website if
using linux then install using the below commands or follow the instructions given on the
website

  1. # command to install
  2. sudo apt-get install redis-server
  3. # command to run server
  4. redis-server
  5. # command to check if running
  6. redis-cli ping
  7. # output
  8. PONG

Now using pipenv create a virtualenv and
install the libraries, if pipenv is not installed then install it using pip

  1. # install pipenv using
  2. pip install pipenv
  3. # command to create virtualenv
  4. pipenv install django django-redis djangorestframework
  5. # command to activate env
  6. pipenv shell

Two new files will be made by pipenv —> Pipfile and Pipfile.lock

Project Setup

start django project

  1. django-admin startproject django_cache .

run migrations and server

  1. python manage.py migrate
  2. python manage.py runserver

start app store

  1. python manage.py startapp store

Configure project settings

  1. INSTALLED_APPS = [
  2. 'django.contrib.admin',
  3. 'django.contrib.auth',
  4. 'django.contrib.contenttypes',
  5. 'django.contrib.sessions',
  6. 'django.contrib.messages',
  7. 'django.contrib.staticfiles',
  8. # django apps
  9. 'store',
  10. # packages
  11. 'rest_framework',
  12. ]

To start using django-redis, you should change your Django cache settings to
something like this:

  1. CACHES = {
  2. "default": {
  3. "BACKEND": "django_redis.cache.RedisCache",
  4. "LOCATION": "redis://127.0.0.1:6379/1",
  5. "OPTIONS": {
  6. "CLIENT_CLASS": "django_redis.client.DefaultClient",
  7. }
  8. }
  9. }

Configure as session backend:

  1. SESSION_ENGINE = "django.contrib.sessions.backends.cache"
  2. SESSION_CACHE_ALIAS = "default"

For complete code for django checkout the project files.

loadtest

Install loadtest using npm

  1. npm install -g loadtest

Don’t forget to run django server before running loadtest command as well as redis-server:

  1. # run these commands from separate terminals or command prompts
  2. python manage.py runserver
  3. redis-server

Run the below command to test the performance of our application

  1. # command that runs 1000 requests with -k = keep connection alive and the url at last
  2. loadtest -n 1000 -k http://localhost:8000/store/
  3. # output
  4. INFO Target URL: http://127.0.0.1:8000/store/
  5. ...
  6. INFO Max requests: 1000
  7. ...
  8. INFO Completed requests: 100
  9. ...
  10. INFO Requests per second: 41
  11. ...

Check your terminal for more detailed results from loadtest command.

Cached View

  1. from django.shortcuts import render
  2. from django.core.cache import cache
  3. from django.conf import settings
  4. from django.core.cache.backends.base import DEFAULT_TIMEOUT
  5. from rest_framework.decorators import api_view
  6. from rest_framework.response import Response
  7. from rest_framework import status
  8. from .models import Product
  9. CACHE_TTL = getattr(settings, 'CACHE_TTL', DEFAULT_TIMEOUT)
  10. ...
  11. # view for cached products
  12. @api_view(['GET'])
  13. def view_cached_products(request):
  14. if 'product' in cache:
  15. products = cache.get('product')
  16. return Response(data=products, status=status.HTTP_201_CREATED)
  17. else:
  18. products = Product.objects.all()
  19. results = [product.to_json() for product in products]
  20. # store products in cache
  21. cache.set('product', results, timeout=CACHE_TTL)
  22. return Response(data=results, status=status.HTTP_201_CREATED)

The code above will check if the key product is present in the cache, and if found, the
data represented will be returned to the browser. In the event that no data is present
in the cache, we first retrieve the data from the database, store it in the cache, and
then return the data queried to the browser.

Now that we have cached our view we can carry our tests again but this time with cached view.

  1. loadtest -n 1000 -k http://127.0.0.1:8000/store/cache
  2. # increased number of requests per second
  3. INFO Requests per second: 248

The first time you hit the endpoint localhost:8000/store/cache, the application will
query from the database and return data, but subsequent calls to the URL will bypass the
database and query from the cache since the data is already available in the cache.

You can check if the key 'product' is stored in cache or not by

  1. python manage.py shell
  2. # import cache and get the 'product' key
  3. from django.core.cache import cache
  4. cache.get('product')
  5. # output
  6. [{'name': 'hedphones',
  7. 'description': 'best audio with non blocking IO',
  8. 'price': '49.99',
  9. 'timestamp': '2018-10-17 03:53:56.850768+00:00',
  10. 'updated': '2018-10-17 03:53:56.850768+00:00'}]

Try increasing the number of requests in loadtest and testing out the cached django
application.