python-3.xdjangodjango-cache

Django MemcacheUnexpectedCloseError and [WinError 10061] No connection could be made because the target machine actively refused it


Hi I am new at django and trying to use django-cache to speed up page load that will list out 100 companies and their details per page but I am constantly running into errors. When I use the IP and Port from the django doc 127.0.0.1:11211 I get this error:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/

Django Version: 3.2.4
Python Version: 3.9.1
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'debug_toolbar',
 'mailer')
Installed Middleware:
('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')



Traceback (most recent call last):
  File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\decorators.py", line 122, in _wrapped_view
    result = middleware.process_request(request)
  File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\middleware\cache.py", line 145, in process_request
    cache_key = get_cache_key(request, self.key_prefix, 'GET', cache=self.cache)
  File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\cache.py", line 362, in get_cache_key
    headerlist = cache.get(cache_key)
  File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\cache\backends\memcached.py", line 77, in get
    return self._cache.get(key, default)
  File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\hash.py", line 361, in get
    return self._run_cmd('get', key, None, *args, **kwargs)
  File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\hash.py", line 334, in _run_cmd
    return self._safely_run_func(
  File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\hash.py", line 214, in _safely_run_func
    result = func(*args, **kwargs)
  File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\base.py", line 619, in get
    return self._fetch_cmd(b'get', [key], False).get(key, default)
  File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\base.py", line 1018, in _fetch_cmd
    self._connect()
  File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\base.py", line 420, in _connect
    sock.connect(sockaddr)

Exception Type: ConnectionRefusedError at /
Exception Value: [WinError 10061] No connection could be made because the target machine actively refused it

And if I use IP and Port given in web browser 127.0.0.1:8000 I get this error:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/

Django Version: 3.2.4
Python Version: 3.9.1
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'debug_toolbar',
 'mailer')
Installed Middleware:
('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')



Traceback (most recent call last):
  File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\decorators.py", line 122, in _wrapped_view
    result = middleware.process_request(request)
  File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\middleware\cache.py", line 145, in process_request
    cache_key = get_cache_key(request, self.key_prefix, 'GET', cache=self.cache)
  File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\cache.py", line 362, in get_cache_key
    headerlist = cache.get(cache_key)
  File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\cache\backends\memcached.py", line 77, in get
    return self._cache.get(key, default)
  File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\hash.py", line 361, in get
    return self._run_cmd('get', key, None, *args, **kwargs)
  File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\hash.py", line 334, in _run_cmd
    return self._safely_run_func(
  File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\hash.py", line 214, in _safely_run_func
    result = func(*args, **kwargs)
  File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\base.py", line 619, in get
    return self._fetch_cmd(b'get', [key], False).get(key, default)
  File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\base.py", line 1027, in _fetch_cmd
    buf, line = _readline(self.sock, buf)
  File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\base.py", line 1440, in _readline
    raise MemcacheUnexpectedCloseError()

Exception Type: MemcacheUnexpectedCloseError at /
Exception Value:

I just cant figure out whats wrong please help. Here are some of my python files:

views.py

from django.views.generic import ListView

from mailer.models import Company


class IndexView(ListView):
    template_name = "mailer/index.html"
    model = Company
    paginate_by = 100

settings.py



# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
from pathlib import Path


# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = someKey

DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
INTERNAL_IPS = ['127.0.0.1', '0.0.0.0']

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'debug_toolbar',
    'mailer',
    #'mailer.management.commands.datafeeder',
)

MIDDLEWARE = (
    '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',
    # 'django.middleware.cache.UpdateCacheMiddleware',
    # 'django.middleware.common.CommonMiddleware',
    # 'django.middleware.cache.FetchFromCacheMiddleware',
)

ROOT_URLCONF = 'djangochallenge.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'djangochallenge.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


STATIC_URL = '/static/'
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

STATIC_URL = '/static/'

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache',
        'LOCATION': '127.0.0.1:8000',
    }
}

urls.py


from django.conf.urls import include, url
from django.views.decorators.cache import cache_page
from mailer.views import IndexView

app_name = 'mailer'

urlpatterns = [
    url(r'^$', cache_page(60*60)(IndexView.as_view()), name="index"),
]

Please let me know if anything more is required to answer this question.


Solution

    1. You've configured your cache backend to use a Memcached server at 127.0.0.1:8000. That's likely a misconfiguration, since your Django development server would run at 127.0.0.1:8000 by default. The default port for Memcached is 11211 – you might want 127.0.0.1:11211.
    2. Have you downloaded Memcached and started it? Are you sure there's a Memcached instance listening?