Django per-view caching not caching - django

I am trying to setup per-view caching and have read the docs a few times, though it still doesn't work.
I do see Memcache being used, but it doesn't seem to be the views as a timestamp I have there is updated.
MIDDLEWARE_CLASSES = (
'django.middleware.gzip.GZipMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'web.middleware.WebMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
'django.middleware.http.ConditionalGetMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.cache.UpdateCacheMiddleware',
)
# Memcache
os.environ['MEMCACHE_SERVERS'] = os.environ.get('MEMCACHIER_SERVERS', '').replace(',', ';')
os.environ['MEMCACHE_USERNAME'] = os.environ.get('MEMCACHIER_USERNAME', '')
os.environ['MEMCACHE_PASSWORD'] = os.environ.get('MEMCACHIER_PASSWORD', '')
CACHES = {
'default': {
'BACKEND': 'django_pylibmc.memcached.PyLibMCCache',
'TIMEOUT': 500,
'BINARY': True,
'OPTIONS': { 'tcp_nodelay': True }
}
}
# URL conf
cache_ttl = 24 * 60 * 60
url(r'^categories/$', cache_page(cache_ttl)(main.categories)),
# View
#ensure_csrf_cookie
def categories(request):

I think there are some mistakes in your code :)
UpdateCacheMiddleware must be the first middleware and FetchFromCacheMiddleware must be the last (https://docs.djangoproject.com/en/dev/topics/cache/#the-per-site-cache)
Dont know if 'django_pylibmc' is a shortcut in your cachebackend but in my settings it is "django.core.cache.backends.memcached.PyLibMCCache"
Maybe that helps.

Related

No 'Access-Control-Allow-Origin' header on the requested resource in Django

I have read relevant question and understand what is cors.
I followed each step.
Install
pip install django-cors-headers
Add
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'a9.core.access.middleware.AccessMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
INSTALLED_APPS = ['corsheaders','otree']
And
python3 manage.py migrate
However, I still get the error:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.1
Is there something I am missing to make it work correctly?
Using 127.0.0.1 NOT localhost did the trik.

Django 1.8 request.user is removed

I am using django 1.8 along with mongoengine and a custom Middleware that is supposed to add a user and a toked to a django request.
These two are passed in the header of the request.
The middleware class is the following :
from models import MongoToken
class TokenAuthenticationMiddleware(object):
def process_request(self, request):
if "HTTP_AUTHORIZATION" not in request.META:
return
tokenkey = get_authorization_header(request).split()[1]
token = MongoToken.objects.get(key=tokenkey)
user = User.objects.get(username=request.META.get("HTTP_USERNAME"))
if token.key == tokenkey and token.user.is_active:
request.user = user
request.token = tokenkey
I also put this in my MIDDLEWARE_CLASSES block of the settings.py files:
MIDDLEWARE_CLASSES = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'myproject.middleware.MongoAuthenticationMiddleware',
'myproject.middleware.TokenAuthenticationMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
And when the considered view is reached, my token is here because thanks to the header params but the user is Null.
Then I am wondering if I did something wrong with this because it does not work.
Thank you for your help.
Alex.

django Cache only gets set on page reload

I am trying my hands around using memcache with django on per-view cache.
The trouble is cache only gets set if i refresh a page,clicking on same link does not sets the cache.(that is if i set cache_view on dispatch and reload page, i see the number of queries fall down to 3-4 queries otherwise on clicking the same link, cache is not set, and i get the same number of queries even after hitting the same url again and again)
Here is my views:
class ProductCategoryView(TemplateView):
"""
Browse products in a given category
"""
context_object_name = "products"
template_name = 'catalogue/category.html'
enforce_paths = True
#method_decorator(cache_page(30))
def dispatch(self, request, *args, **kwargs):
return super(ProductCategoryView, self).dispatch(request, *args, **kwargs)
My cache settings is:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
My middlewares are:
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
'oscar.apps.basket.middleware.BasketMiddleware',
'django.middleware.transaction.TransactionMiddleware',
)
Thanks.

django cache not working as expected

I'd like to add simple cache functionality to my site. I have enabled cache for anonymous users, but it does not work as expected. I'm using memcached.
settings.py
########################### caching #################################
CACHE_PORT = '11211'
CACHE_MIDDLEWARE_SECONDS = 60
CACHE_MIDDLEWARE_KEY_PREFIX = "default"
CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True
# Production Environment
if ON_OPENSHIFT:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '%s:%s' % (os.environ['OPENSHIFT_INTERNAL_IP'], CACHE_PORT),
}
}
CACHE_VIEW_LENGTH = datetime.now() + timedelta(30) # 30 day cache expiration
# Development Environment
else:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:%s' % CACHE_PORT,
}
}
CACHE_VIEW_LENGTH = datetime.now() + timedelta(1) # Set to 0 for development
MIDDLEWARE_CLASSES = (
#cache - must be first in middleware_classes
'django.middleware.cache.UpdateCacheMiddleware',
#cache end
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
'django.middleware.clickjacking.XFrameOptionsMiddleware',
#cache - must be last in middleware_classes
'django.middleware.cache.FetchFromCacheMiddleware',
#cache end
)
Since I have set CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True, I would except that if I load page as logged in user, I would not get cached version.
I loaded index page where is list of my objects. There are 10 objects. I added new object through form. When I checked on my index page again, I see only 10 objects.
So my question is simple: Why is django ignoring my setting for anonymous only and caches pages for logged in users?
CACHE_MIDDLEWARE_ANONYMOUS_ONLY option was removed in Django 1.8. Here is the ticket about that: https://code.djangoproject.com/ticket/15201
When CACHE_MIDDLEWARE_ANONYMOUS_ONLY was working, it was only about writing to cache. When CACHE_MIDDLEWARE_ANONYMOUS_ONLY is True, non-anonymous request never writes to cache, but reads from cache.

django cms language change

This is my sort of setting .py
CMS_LANGUAGE_CONF = {
'en':['es'],
'es':['en'],
}
CMS_SITE_LANGUAGES = {
1:['en','es'],
}
CMS_LANGUAGES = (
('es', gettext('Spanish')),
('en', gettext('English')),
)
CMS_HIDE_UNTRANSLATED = True
LANGUAGES = [('es', 'Spanish'),('en', 'English')]
DEFAULT_LANGUAGE = 1
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'cms.middleware.page.CurrentPageMiddleware',
'cms.middleware.user.CurrentUserMiddleware',
'cms.middleware.toolbar.ToolbarMiddleware',
# 'django.middleware.locale.LocaleMiddleware',
'cms.middleware.multilingual.MultilingualURLMiddleware',
# 'vclubcms.middleware.URLMiddlewares.CustomMultilingualURLMiddleware'
)
My problem is :
when i access myserver:8000/myview it renders.
when i access myserver:8000/cmspage it renders
on the cms page templage i have some links . which get converted to /language_code/cmspage due to multilingual. so when click on link it is not opening .
e.g. myserver:8000/language_code/cmspage not working
What i tried i followed this link
http://ilian.i-n-i.org/language-redirects-for-multilingual-sites-with-django-cms/comment-page-1/
and enable the
'vclubcms.middleware.URLMiddlewares.CustomMultilingualURLMiddleware'
and then i run the myserver:8000/language_code/cmspage
it shows
The page isn't redirecting properly
and with 21 request.
Please suggest how can i solve this problem .