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.
Related
I implemented Django middleware for dynamic logo, site title, etc. It is working very slowly.
example. When I updated my site title, it was not updated instantly. But when I server restarted It is working.
this is my code
class AppBasicInfo():
def __init__(self, get_response):
self.site = SiteInfo.objects.first() if SiteInfo.objects.first() else "Not Implemented"
self.get_response = get_response
def __call__(self, request, *args, **kwargs):
request.site = self.site
response = self.get_response(request)
return response
settings file
MIDDLEWARE = [
'blog.middleware.AppBasicInfo',
'django.middleware.security.SecurityMiddleware',
'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',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'blog.middleware.AppMenu',
'blog.middleware.SocialIcon',
'blog.middleware.DynamicYear',
]
and I call middleware variable as my template like {{request.site.site_title}}
__init__ is called only once, try moving
self.site = SiteInfo.objects.first() if SiteInfo.objects.first() else "Not Implemented"
to __call__
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.
I am struggling getting MiddleWare to work. I put this in my settings.py:
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'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',
'portal.middleware.SimpleMiddleware'
]
and I implemented this class in portal/middleware/MiddleWare.py:
class SimpleMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
response = self.get_response(request)
# Code to be executed for each request/response after
# the view is called.
return response
But when running, I get a TypeError:
TypeError: __init__() takes exactly 2 arguments (1 given)
Since you are writing a new-style middleware, you should use MIDDLEWARE instead of MIDDLEWARE_CLASSES in your settings.
You also need to make sure that your entry in the settings matches the location of the middleware. The entry 'portal.middleware.SimpleMiddleware' suggests a SimpleMiddleware class in portal/middleware.py, which does not match your filename portal/middleware/MiddleWare.py.
I have a website I have built in Django 1.8 which must load in a Box.com iframe. However it is not loading in Chrome and I get the x-frame-options SAMEORIGIN error.
But I have added the following middleware classes:
MIDDLEWARE_CLASSES = (
# Default Django middleware.
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
and in my views.py added the xframe_options_exempt decorator like so:
#api_view(['GET'])
#xframe_options_exempt
def category_list(request):
"""
List all categories.
"""
if request.method == 'GET':
categories = Category.objects.order_by('-category_type')
serializer = CategorySerializer(categories, many=True)
return Response(serializer.data)
Plus I have tried adding the following setting with no luck:
X_FRAME_OPTIONS = 'ALLOW-FROM https://app.box.com/'
Can anyone help me discover why this is still not allowing the page to load?
Do I also need to add the decorator function in urls.py like this?
from django.views.decorators.clickjacking import xframe_options_exempt
urlpatterns = patterns('base.views',
url(r'^categories$', xframe_options_exempt(category_list)),
)
Thanks very much for any help.
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.