{"id":20455360,"url":"https://github.com/alexmhack/django-cache","last_synced_at":"2026-04-16T14:02:32.783Z","repository":{"id":49692664,"uuid":"153388619","full_name":"Alexmhack/Django-Cache","owner":"Alexmhack","description":"Using redis and django-redis to perform caching for the django application","archived":false,"fork":false,"pushed_at":"2022-12-08T01:16:19.000Z","size":19,"stargazers_count":1,"open_issues_count":4,"forks_count":1,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-10-09T02:44:18.589Z","etag":null,"topics":["caching","database","django-application","django-cache","django-caching","django-redis","loadtest","pipenv","tutorial"],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Alexmhack.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-10-17T03:13:15.000Z","updated_at":"2023-08-27T01:35:57.000Z","dependencies_parsed_at":"2023-01-25T02:31:02.664Z","dependency_job_id":null,"html_url":"https://github.com/Alexmhack/Django-Cache","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Alexmhack/Django-Cache","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Alexmhack%2FDjango-Cache","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Alexmhack%2FDjango-Cache/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Alexmhack%2FDjango-Cache/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Alexmhack%2FDjango-Cache/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Alexmhack","download_url":"https://codeload.github.com/Alexmhack/Django-Cache/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Alexmhack%2FDjango-Cache/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279004916,"owners_count":26083803,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-10T02:00:06.843Z","response_time":62,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["caching","database","django-application","django-cache","django-caching","django-redis","loadtest","pipenv","tutorial"],"created_at":"2024-11-15T11:18:39.580Z","updated_at":"2025-10-10T18:44:13.976Z","avatar_url":"https://github.com/Alexmhack.png","language":"Python","readme":"# Django-Cache\nUsing redis and django-redis to perform caching for the django application\n\nIn this tutorial we will be setting up [Redis]() and [Django] using [django-redis] and \nenable caching for our django web application.\n\nCaching refers to storing the server response in the client itself, so that a client need \nnot make a server request for the same resource again and again. A server response should \nhave information about how caching is to be done, so that a client caches the response \nfor a time period or never caches the server response.\n\n## Installation\nFirst of all install [Redis](https://redis.io/download) from the official website if \nusing linux then install using the below commands or follow the instructions given on the \n[website](https://redis.io/download)\n\n```\n# command to install\nsudo apt-get install redis-server\n\n# command to run server\nredis-server\n\n# command to check if running\nredis-cli ping\n\n# output\nPONG\n```\n\nNow using [pipenv](https://pipenv.readthedocs.io/en/latest/) create a virtualenv and \ninstall the libraries, if pipenv is not installed then install it using pip\n\n```\n# install pipenv using\npip install pipenv\n\n# command to create virtualenv\npipenv install django django-redis djangorestframework\n\n# command to activate env\npipenv shell\n```\n\nTwo new files will be made by **pipenv** --\u003e ```Pipfile``` and ```Pipfile.lock```\n\n## Project Setup\n**start django project**\n```\ndjango-admin startproject django_cache .\n```\n\n**run migrations and server**\n```\npython manage.py migrate\npython manage.py runserver\n```\n\n**start app store**\n```\npython manage.py startapp store\n```\n\n**Configure project settings**\n\n```\nINSTALLED_APPS = [\n    'django.contrib.admin',\n    'django.contrib.auth',\n    'django.contrib.contenttypes',\n    'django.contrib.sessions',\n    'django.contrib.messages',\n    'django.contrib.staticfiles',\n\n    # django apps\n    'store',\n\n    # packages\n    'rest_framework',\n]\n```\n\nTo start using **django-redis**, you should change your Django cache settings to \nsomething like this:\n\n```\nCACHES = {\n    \"default\": {\n        \"BACKEND\": \"django_redis.cache.RedisCache\",\n        \"LOCATION\": \"redis://127.0.0.1:6379/1\",\n        \"OPTIONS\": {\n            \"CLIENT_CLASS\": \"django_redis.client.DefaultClient\",\n        }\n    }\n}\n```\n\nConfigure as **session backend**:\n\n```\nSESSION_ENGINE = \"django.contrib.sessions.backends.cache\"\nSESSION_CACHE_ALIAS = \"default\"\n```\n\nFor complete code for django checkout the project files.\n\n## [loadtest](https://www.npmjs.com/package/loadtest)\nInstall loadtest using npm\n\n\n```\nnpm install -g loadtest\n```\n\n**Don't forget to run django server before running loadtest command as well as redis-server**:\n\n```\n# run these commands from separate terminals or command prompts\npython manage.py runserver\nredis-server\n```\n\nRun the below command to test the performance of our application\n```\n# command that runs 1000 requests with -k = keep connection alive and the url at last\nloadtest -n 1000 -k  http://localhost:8000/store/\n\n# output\nINFO Target URL:          http://127.0.0.1:8000/store/\n...\nINFO Max requests:        1000\n...\nINFO Completed requests:  100\n...\nINFO Requests per second: 41\n...\n```\n\nCheck your terminal for more detailed results from loadtest command.\n\n## Cached View\n\n```\nfrom django.shortcuts import render\nfrom django.core.cache import cache\nfrom django.conf import settings\nfrom django.core.cache.backends.base import DEFAULT_TIMEOUT\n\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom rest_framework import status\n\nfrom .models import Product\n\nCACHE_TTL = getattr(settings, 'CACHE_TTL', DEFAULT_TIMEOUT)\n...\n\n# view for cached products\n@api_view(['GET'])\ndef view_cached_products(request):\n\tif 'product' in cache:\n\t\tproducts = cache.get('product')\n\t\treturn Response(data=products, status=status.HTTP_201_CREATED)\n\telse:\n\t\tproducts = Product.objects.all()\n\t\tresults = [product.to_json() for product in products]\n\n\t\t# store products in cache\n\t\tcache.set('product', results, timeout=CACHE_TTL)\n\t\treturn Response(data=results, status=status.HTTP_201_CREATED)\n```\n\nThe code above will check if the key product is present in the cache, and if found, the \ndata represented will be returned to the browser. In the event that no data is present \nin the cache, we first retrieve the data from the database, store it in the cache, and \nthen return the data queried to the browser.\n\nNow that we have cached our view we can carry our tests again but this time with cached view.\n\n```\nloadtest -n 1000 -k http://127.0.0.1:8000/store/cache\n\n# increased number of requests per second\nINFO Requests per second: 248\n```\n\nThe first time you hit the endpoint localhost:8000/store/cache, the application will \nquery from the database and return data, but subsequent calls to the URL will bypass the \ndatabase and query from the cache since the data is already available in the cache.\n\nYou can check if the key ```'product'``` is stored in cache or not by\n\n```\npython manage.py shell\n\n# import cache and get the 'product' key\nfrom django.core.cache import cache\ncache.get('product')\n\n# output\n[{'name': 'hedphones',\n  'description': 'best audio with non blocking IO',\n  'price': '49.99',\n  'timestamp': '2018-10-17 03:53:56.850768+00:00',\n  'updated': '2018-10-17 03:53:56.850768+00:00'}]\n```\n\nTry increasing the number of requests in loadtest and testing out the cached django \napplication.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falexmhack%2Fdjango-cache","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Falexmhack%2Fdjango-cache","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falexmhack%2Fdjango-cache/lists"}