django memcahed key generation - django

Default django cache keys generator:
def make_key(key, key_prefix, version):
return ':'.join([key_prefix, str(version), key])
I want to change with:
in settings.py
def make_key(key, key_prefix, version):
return key
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
'KEY_FUNCTION' : 'settings.make_key',
}
}
but django generate keys with old native function (prefix-version-key) how to change it?

Try:
def make_key(key, key_prefix, version):
return key
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
'KEY_FUNCTION' : make_key
}
}
I know that in documentation is "string containing a dotted path" but I see in the Django source code that you can also pass callable object (eg. function).
If you really need to pass it as a string, you should move this function to another module and set yourproject.module.make_key as KEY_FUNCTION.

Related

Django Redis Caching how can i set cache timeout to none (never expiring cache) in class base view

I'm using redis server for caching. Using django-redis package.
Below is my setting file :
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://127.0.0.1:6379/1',
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
},
}
}
My view :
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
#method_decorator(cache_page(timeout=None,key_prefix="site1"), name='dispatch')
class ProfileView(APIView):
# With auth: cache requested url for each user for 2 hours
def get(self, request, format=None):
content = {
'user_feed': request.user.get_user_feed()
}
return Response(content)
When set timeout=60 it's working. But when i add timeout=None i'm getting 600 seconds timeout.

Cutomize dj_rest_auth Password reset email

I want to send customized emails when a user request a password reset. I am using dj_rest_auth with django. Here is what I have done: 1. Defined a custom serializer that inherits from PasswordResetSerializer of dj_rest_auth
class CustomPasswordResetSerializer(PasswordResetSerializer):
def get_email_options(self):
return {
'html_mail_template_name': 'registration/password_reset_email.html',
}
Then in settings.py pointed to this serializer:
REST_AUTH_SERIALIZERS = {
'LOGIN_SERIALIZER': 'users.serializers.CustomLoginSerializer',
'PASSWORD_RESET_SERIALIZER': 'users.serializers.CustomPasswordResetSerializer',
}
Then configured templates in settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Then I created templates folder in project root, created a registration folder inside it and placed password_reset_email.html inside it.
This is what I found as an exact solution formy problem after googling some time,but this is not working for me. What did I miss?
This answer helped me
https://stackoverflow.com/a/70624462/15624533
I just put my files (html or txt) directly to templates folder, and changed 'account/email/password_reset_key' to just 'password_reset_key' in send_mail method.
I faced the same challenge and got the solution from this issue on GitHub. https://github.com/iMerica/dj-rest-auth/issues/9 . It's easier than you think
Create your custom password reset serializer
from dj_rest_auth.serializers import PasswordResetSerializer
class CustomPasswordResetSerializer(PasswordResetSerializer):
def save(self):
request = self.context.get('request')
# Set some values to trigger the send_email method.
opts = {
'use_https': request.is_secure(),
'from_email': 'example#yourdomain.com',
'request': request,
# here I have set my desired template to be used
# don't forget to add your templates directory in settings to be found
'email_template_name': 'password_reset_email.html'
}
opts.update(self.get_email_options())
self.reset_form.save(**opts)
If you only want to customize email parameters nothing more or less, you can ignore overriding save() method and override get_email_options() instead
from dj_rest_auth.serializers import PasswordResetSerializer
class MyPasswordResetSerializer(PasswordResetSerializer):
def get_email_options(self) :
return {
'email_template_name': 'password_reset_email.html'
}
then point to your custom serializer in settings.py
REST_AUTH_SERIALIZERS = {
'PASSWORD_RESET_SERIALIZER': 'path.to.your.CustomPasswordResetSerializer'
}

I am trying to integrate filebased session in django

I am trying to integrate filebased session in django. I have followed all the provided details But session is not working.
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
'LOCATION': '/var/tmp/django_cache',
}
}
I am getting below error
Exception Type: OperationalError
Exception Value:
no such table: django_session
Looks like you confused caching and session frameworks. Your current settings is affecting only cache system. To use file based session you need to add SESSION_ENGINE and SESSION_FILE_PATH settings:
SESSION_ENGINE = "django.contrib.sessions.backends.file"
SESSION_FILE_PATH = "/var/tmp/django_cache"

Getting caching working with Django

We are trying to implement caching in Django. We have tried memcache, file system caching and local memory caching. No mater what it just isn't working -- a timestamp we put on the template to test caching is always updating so we know it's not working.
Here are relevant portions of code.
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
'LOCATION': 'c:/tmp',
}
}
CACHE_MIDDLEWARE_ALIAS = "default"
CACHE_MIDDLEWARE_SECONDS = 600
MIDDLEWARE_CLASSES = [
"django.middleware.cache.UpdateCacheMiddleware",
... OTHER ONES ...
"django.middleware.cache.FetchFromCacheMiddleware",
]
VIEWS.PY
from django.views.decorators.cache import cache_page
#cache_page(60 * 10)
def profiles(request, template_name="profiles/profiles.html", extra_context=None):
...

Django multiple caching BACKEND routers howto?

So I want to cache some data in mysql and some in memcached.
at the moment I have this In my config file, but i don't know how to write router for cache back end.
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
I use multi databases structure and I know how to write multi database routers.
in settings.py
DATABASE_ROUTERS = ['oceankeys.dbrouter.SphinxRouter','oceankeys.dbrouter.DefaultDbRouter']
Any one know how to make Django caching BACKEND router?
Thanks
I don't believe the Django cache framework can mimic db routing in general.
For the site cache using the cache framework middleware you have to specify the name of the cache in settings.py, e.g.:
CACHE_MIDDLEWARE_ALIAS = "my_cache_alias"
For a page cache you can manually specify the name of the cache in the decorator, e.g.:
#cache_page(60 * 15, cache="my_cache_alias")
def my_view(request):
...
I'm not sure cache routing really makes sense for site and page caching so I don't have a problem with the way this is designed.
Now, for your case where you are using MySQL as a database cache backend you can set it up and make a router as per the Django docs section on database caching. For example, this would be your CACHES setting:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
'my_cache_alias': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'my_cache_table',
}
}
Then create a router that identifies which cache backend to use for which models. It looks and works exactly like DB router (as you should be able to see from the doc section on database caching and multiple databases) with the exception that it returns a cache alias instead of db alias.
e.g
settings.py
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
},
'myalias':{
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'my_cache_table',
}
}
views.py
from django.core.cache import caches
cache = caches['myalias']
cache.set('my_key', 'hello, world!', 30)
print cache.get('my_key')
You can see the detail in Django’s cache framework (section:Accessing the cache)