django cache not working as expected - django

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.

Related

django-session-timeout: how to disconnect automatically (without user action)

I am newbie in Django and try to implement 'autologout' using a tierce app django-session-timeout
It works but I would like to improve behavior
the session expire after time set in settings.py but there is no refresh so that it is disconnect and redirect to login page except if user click elsewhere
in other word, the user is disconnect (as user session expire) but not automatically redirect to login page -> need a user event
is it possible to improve this without writing my own middleware?
settings.py
MIDDLEWARE = [
'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',
'django_session_timeout.middleware.SessionTimeoutMiddleware',
]
LOGIN_URL = 'home'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
SESSION_EXPIRE_SECONDS = 900 # 900 - >15 minutes = 15 * 60
SESSION_EXPIRE_AFTER_LAST_ACTIVITY = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_SAVE_EVERY_REQUEST = True

Windows authentication with Django and Angular?

I am trying to implement the single sign-on using Angular, Django, IIS server.
In IIS windows authentication is enabled.
Angular intercepter code :
intercept(req: HttpRequest<any>, next: HttpHandler):Observable<HttpEvent<any>> {
console.log("in intercept")
req = req.clone({
withCredentials: true });
return next.handle(req); }
Django settings.py:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',]
AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.RemoteUserBackend',)
CORS_ORIGIN_ALLOW_ALL = True
ALLOWED_HOSTS = ["*"]
Getting error:
(IP-address) has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Try this configuration in settings.py
CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_CREDENTIALS = True # This one is required when you are using withCredentials: true
The problem will lie in the Django setup, please have a look at this link: https://stackoverflow.com/a/38162454/4587598
If at first try won't work, strip all settings.py and setup from scratch, firstly checking if CORS issue does not occur and afterwards add authentication complexity.
try django-cors-headers
pip install django-cors-headers
And set it up
In your settings.py
INSTALLED_APPS = (
...
'corsheaders',
...
)
You will also need to add a middleware class to listen in on responses:
MIDDLEWARE = [ # Or MIDDLEWARE_CLASSES on Django < 1.10
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
CorsMiddleware should be placed as high as possible, especially before any middleware that can generate responses such as Django's CommonMiddleware
CORS_ORIGIN_ALLOW_ALL = True

Django Filesystem Caching

I'm trying to get entire-site filesystem based caching working for the first time.
I've created /var/tmp/django_cache with 777 permissions.
I've added this to settings.py:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
'LOCATION': '/var/tmp/django_cache',
'TIMEOUT': 60,
'OPTIONS': {
'MAX_ENTRIES': 1000
}
}
}
CACHE_MIDDLEWARE_ALIAS = 'default'
CACHE_MIDDLEWARE_SECONDS = 60
CACHE_MIDDLEWARE_KEY_PREFIX = 'myapp'
And I've updated the relevant part of the middleware classes:
MIDDLEWARE_CLASSES = (
....
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
...
)
Is there anything else I need to do? I'm not seeing any files get created in /var/tmp/django_cache when I browse around. I touched wsgi.py, restarted apache. No dice.

How to achieve LDAP authentication in Django, How to access User object in View?

I want to build a site using Django wherein to enter it, the users have to authenticate themselves through LDAP server.
I have read the python-ldap configuration and configured settings.py accordingly. I'm able to authenticate a user from local database, but when I try to do it through LDAP, it doesn't work.
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DIRS = [os.path.join(BASE_DIR,'templates')]
import ldap
from django_auth_ldap.config import LDAPSearch, GroupOfNamesType
# Baseline configuration.
AUTH_LDAP_SERVER_URI = "ldap://10.1.10.10"
AUTH_LDAP_CONNECTION_OPTIONS = {
ldap.OPT_REFERRALS: 0
}
AUTH_LDAP_BIND_DN = "cn=myname,dc=example,dc=com"
AUTH_LDAP_BIND_PASSWORD = "dontevenask"
AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=users,dc=example,dc=com",
ldap.SCOPE_SUBTREE, "(uid=%(user)s)")
#AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s,ou=users,dc=example,dc=com"
AUTH_LDAP_USER_ATTR_MAP = {
"first_name": "givenName",
"last_name": "sn",
"email": "mail"
}
AUTH_LDAP_ALWAYS_UPDATE_USER = True
AUTH_LDAP_FIND_GROUP_PERMS = True
AUTHENTICATION_BACKENDS = (
'django_auth_ldap.backend.LDAPBackend',
'django.contrib.auth.backends.ModelBackend',
)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '^eh5xdkui7vw!^x&l%q44ak6+yglnx5q(tqwd8l+w!sxml7q!&'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'my_app',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'users.urls'
WSGI_APPLICATION = 'users.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS':{
'read_default_file':'/home/user/config.cnf',
},
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
Here is my views.py file
def loggedin(request):
uid = request.user.username
return render_to_response('loggedin.html',
{'full_name':uid})
And the loggedin.html file
{% block content %}
<h2> Hi {{full_name}} Logged in! </h2>
<p> Click here to logout </p>
{% endblock %}
I did refer to other posts but didn't find the solution.
What am I missing?
There are several issues that might cause the LDAP authentication not to work.
I am assuming you are running linux host. Have you verified that the LDAP settings you have entered works properly? Use command line tool 'ldapsearch' verify that the server works and responses as you might expect.
After you have successfully authenticated with ldapsearch and the authentication is still not working in Django i suggest you put logging on on and paste the logs somewhere.
Without futher info its hard to say what part of your setup is incorrect.
So, here goes the answer!
I changed "(uid=%(user)s)") to "(samaccountname=%(user)s)") which did the trick.
Having the logger helped locate what the problem was - was it even talking to LDAP or just trying to authenticate with the local database.

Django per-view caching not caching

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.