【问题标题】:Django MemcacheUnexpectedCloseError and [WinError 10061] No connection could be made because the target machine actively refused itDjango MemcacheUnexpectedCloseError 和 [WinError 10061] 无法建立连接,因为目标机器主动拒绝它
【发布时间】:2021-08-02 11:05:33
【问题描述】:

您好,我是 django 的新手,正在尝试使用 django-cache 来加快页面加载速度,每页将列出 100 家公司及其详细信息,但我经常遇到错误。当我使用 django doc 127.0.0.1:11211 中的 IP 和端口时,我收到此错误:

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

如果我使用网络浏览器中给出的 IP 和端口 127.0.0.1:8000 我会收到此错误:

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:

我只是想不通是什么问题,请帮忙。以下是我的一些 python 文件:

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"),
]

如果还需要回答这个问题,请告诉我。

【问题讨论】:

    标签: python-3.x django django-cache


    【解决方案1】:
    1. 您已将缓存后端配置为使用位于 127.0.0.1:8000 的 Memcached 服务器。这可能是一个错误配置,因为您的 Django 开发服务器默认运行在 127.0.0.1:8000。 Memcached 的默认端口是 11211 - 您可能需要 127.0.0.1:11211。
    2. 您是否下载并启动了 Memcached?你确定有一个 Memcached 实例在监听吗?

    【讨论】:

    • 我已经下载了pymemcache,但是启动它是什么意思?
    • 不一样。 Pymemcache 是一个与 Memcached 服务(服务器)对话的库。似乎很难为 Memcached 找到 Windows 二进制文件。
    • 是的,这很困难,我访问的每个下载链接都会自行崩溃。有没有其他方法可以加快页面加载速度,或者其他使用 django 缓存的方法?
    • 选择不同的缓存后端。出于测试目的,您可以只使用本地内存缓存甚至文件系统缓存。对于生产用途,我推荐 Redis。请参阅 django-redis 包。
    • 感谢您的帮助,会调查的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    • 2020-06-26
    • 1970-01-01
    • 2020-07-07
    • 2021-01-04
    • 2021-02-08
    相关资源
    最近更新 更多