Django, Redis: Where to put connection-code

2024/10/11 12:31:26

I have to query redis on every request in my Django-app. Where can I put the setup/ connection routine (r = redis.Redis(host='localhost', port=6379)) so that I can access and reuse the connection without having to instantiate a new connection in my views?

Answer

Add this line to Settings file for creating connection,

CACHES = {"default": {"BACKEND": "django_redis.cache.RedisCache","LOCATION": "redis://127.0.0.1:6379/1","OPTIONS": {"CLIENT_CLASS": "django_redis.client.DefaultClient"},"KEY_PREFIX": "example"}
}# Cache time to live is 15 minutes.
CACHE_TTL = 60 * 15

View level Cache, It will cache the query response(data)

from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_pageclass TestApiView(generics.ListAPIView):serializer_class = TestSerializer@method_decorator(cache_page(60))def dispatch(self, *args, **kwargs):return super(TestApiView, self).dispatch(*args, **kwargs)

Template level cache,

from django.conf import settings
from django.core.cache.backends.base import DEFAULT_TIMEOUT
from django.shortcuts import render
from django.views.decorators.cache import cache_page
from .services import get_recipes_with_cache as get_recipesCACHE_TTL = getattr(settings, 'CACHE_TTL', DEFAULT_TIMEOUT)@cache_page(CACHE_TTL)
def recipes_view(request):return render(request, 'index.html', {'recipes': get_recipes()})

For any doubts refer this links

  1. How to cache Django Rest Framework API calls?
  2. https://github.com/realpython/django-redis-cache
  3. https://boostlog.io/@nixus89896/setup-caching-in-django-with-redis-5abb7d060814730093a2eebe
https://en.xdnf.cn/q/118325.html

Related Q&A

Events and Bindings in tkinter does not work in loop

I am trying to create binding in a loop using tkinter module.from tkinter import * class Gui(Frame):def __init__(self, parent):Frame.__init__(self, parent) self.parent = parentself.initUI()def Arrays(…

Python Machine Learning Algorithm to Recognize Known Events

I have two sets of data. These data are logged voltages of two points A and B in a circuit. Voltage A is the main component of the circuit, and B is a sub-circuit. Every positive voltage in B is (1) co…

How can I replace Unicode characters in Python?

Im pulling Twitter data via their API and one of the tweets has a special character (the right apostrophe) and I keep getting an error saying that Python cant map or character map the character. Ive lo…

Filtering Pandas DataFrame using a condition on column values that are numpy arrays

I have a Pandas DataFrame called dt, which has two columns called A and B. The values of column B are numpy arrays; Something like this: index A B 0 a [1,2,3] 1 b [2,3,4] 2 c …

Creation a tridiagonal block matrix in python [duplicate]

This question already has answers here:Block tridiagonal matrix python(9 answers)Closed 6 years ago.How can I create this matrix using python ? Ive already created S , T , X ,W ,Y and Z as well as the…

Python tkinter checkbutton value always equal to 0

I put the checkbutton on the text widget, but everytime I select a checkbutton, the function checkbutton_value is called, and it returns 0.Part of the code is :def callback():file_name=askopenfilename(…

How does derived class arguments work in Python?

I am having difficulty understanding one thing in Python.I have been coding in Python from a very long time but theres is something that just struck me today which i struggle to understandSo the situat…

grouping on tems in a list in python

I have 60 records with a column "skillsList" "("skillsList" is a list of skills) and "IdNo". I want to find out how many "IdNos" have a skill in common.How …

How do I show a suffix to user input in Python?

I want a percentage sign to display after the users enters their number. Thankspercent_tip = float(input(" Please Enter the percent of the tip:")("%"))For example, before the user t…

Discord.py Self Bot using rewrite

Im trying to make a selfbot using discord.py rewrite. Im encountering issues when attempting to create a simple command. Id like my selfbot to respond with "oof" when ">>>test&q…