Django Python - 由于目标机器主动拒绝,无法建立连接

Django Python - No connection could be made because the target machine actively refused it

我在 虚拟环境 的硬盘根目录下有一个 Django python 服务器。在命令行中,当我激活 env 和 运行 python manage.py 192.168.0.47:80 它正常启动服务器(没有迁移通知或任何东西),但是当我从浏览器加载页面时(使用 instancegaming.net 在本地,它在我的服务器主机文件中,过去在本地和远程都运行良好)它会永远加载和加载,当我转到 Django 服务器时 window 并执行 Ctrl+C 它会更新控制台并给我以下错误。请记住,此 env 是一个 全新安装 ,除 Django 外没有其他站点包。我之前在同一台服务器 (Windows 10 64-bit) 上成功拥有 运行 服务器,并且具有相同的路由器配置。

我看过其他帖子 像这样 (Python Django-Helpdesk Error: No connection could be made because the target machine actively refused it) 和一些其他帖子,但其中 none 似乎解决了问题.

控制台Window:

(env) C:\server\www>python manage.py runserver 192.168.0.47:80
Performing system checks...

System check identified no issues (0 silenced).
December 28, 2016 - 19:07:06
Django version 1.10.4, using settings 'www.settings'
Starting development server at http://192.168.0.47:80/
Quit the server with CTRL-BREAK.
 Traceback (most recent call last):
  File "C:\server\env\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
    response = get_response(request)
  File "C:\server\env\lib\site-packages\django\utils\deprecation.py", line 136, in __call__
    response = self.get_response(request)
  File "C:\server\env\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = response_for_exception(request, exc)
  File "C:\server\env\lib\site-packages\django\core\handlers\exception.py", line 86, in response_for_exception
    response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
  File "C:\server\env\lib\site-packages\django\core\handlers\exception.py", line 124, in handle_uncaught_exception
    extra={'status_code': 500, 'request': request},
  File "c:\python\Lib\logging\__init__.py", line 1308, in error
    self._log(ERROR, msg, args, **kwargs)
  File "c:\python\Lib\logging\__init__.py", line 1415, in _log
    self.handle(record)
  File "c:\python\Lib\logging\__init__.py", line 1425, in handle
    self.callHandlers(record)
  File "c:\python\Lib\logging\__init__.py", line 1487, in callHandlers
    hdlr.handle(record)
  File "c:\python\Lib\logging\__init__.py", line 855, in handle
    self.emit(record)
  File "C:\server\env\lib\site-packages\django\utils\log.py", line 121, in emit
    self.send_mail(subject, message, fail_silently=True, html_message=html_message)
  File "C:\server\env\lib\site-packages\django\utils\log.py", line 124, in send_mail
    mail.mail_admins(subject, message, *args, connection=self.connection(), **kwargs)
  File "C:\server\env\lib\site-packages\django\core\mail\__init__.py", line 103, in mail_admins
    mail.send(fail_silently=fail_silently)
  File "C:\server\env\lib\site-packages\django\core\mail\message.py", line 342, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "C:\server\env\lib\site-packages\django\core\mail\backends\smtp.py", line 100, in send_messages
    new_conn_created = self.open()
  File "C:\server\env\lib\site-packages\django\core\mail\backends\smtp.py", line 58, in open
    self.connection = connection_class(self.host, self.port, **connection_params)
  File "c:\python\Lib\smtplib.py", line 251, in __init__
    (code, msg) = self.connect(host, port)
  File "c:\python\Lib\smtplib.py", line 335, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "c:\python\Lib\smtplib.py", line 306, in _get_socket
    self.source_address)
  File "c:\python\Lib\socket.py", line 711, in create_connection
    raise err
  File "c:\python\Lib\socket.py", line 702, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

During handling of the above exception, another exception occurred:

 Traceback (most recent call last):
  File "c:\python\Lib\wsgiref\handlers.py", line 137, in run
    self.result = application(self.environ, self.start_response)
  File "C:\server\env\lib\site-packages\django\core\handlers\wsgi.py", line 170, in __call__
    response = self.get_response(request)
  File "C:\server\env\lib\site-packages\django\core\handlers\base.py", line 124, in get_response
    response = self._middleware_chain(request)
  File "C:\server\env\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = response_for_exception(request, exc)
  File "C:\server\env\lib\site-packages\django\core\handlers\exception.py", line 86, in response_for_exception
    response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
  File "C:\server\env\lib\site-packages\django\core\handlers\exception.py", line 124, in handle_uncaught_exception
    extra={'status_code': 500, 'request': request},
  File "c:\python\Lib\logging\__init__.py", line 1308, in error
    self._log(ERROR, msg, args, **kwargs)
  File "c:\python\Lib\logging\__init__.py", line 1415, in _log
    self.handle(record)
  File "c:\python\Lib\logging\__init__.py", line 1425, in handle
    self.callHandlers(record)
  File "c:\python\Lib\logging\__init__.py", line 1487, in callHandlers
    hdlr.handle(record)
  File "c:\python\Lib\logging\__init__.py", line 855, in handle
    self.emit(record)
  File "C:\server\env\lib\site-packages\django\utils\log.py", line 121, in emit
    self.send_mail(subject, message, fail_silently=True, html_message=html_message)
  File "C:\server\env\lib\site-packages\django\utils\log.py", line 124, in send_mail
    mail.mail_admins(subject, message, *args, connection=self.connection(), **kwargs)
  File "C:\server\env\lib\site-packages\django\core\mail\__init__.py", line 103, in mail_admins
    mail.send(fail_silently=fail_silently)
  File "C:\server\env\lib\site-packages\django\core\mail\message.py", line 342, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "C:\server\env\lib\site-packages\django\core\mail\backends\smtp.py", line 100, in send_messages
    new_conn_created = self.open()
  File "C:\server\env\lib\site-packages\django\core\mail\backends\smtp.py", line 58, in open
    self.connection = connection_class(self.host, self.port, **connection_params)
  File "c:\python\Lib\smtplib.py", line 251, in __init__
    (code, msg) = self.connect(host, port)
  File "c:\python\Lib\smtplib.py", line 335, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "c:\python\Lib\smtplib.py", line 306, in _get_socket
    self.source_address)
  File "c:\python\Lib\socket.py", line 711, in create_connection
    raise err
  File "c:\python\Lib\socket.py", line 702, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
[28/Dec/2016 19:08:15] "GET / HTTP/1.1" 500 59

我的settings.py:

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = [
    '.instancegaming.net',
]


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'home',
]

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',
]

ROOT_URLCONF = 'www.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 = 'www.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators

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',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'MST'

USE_I18N = True

USE_L10N = True

USE_TZ = True

ADMINS = (('Jacob J','jacoblj3333@gmail.com'))

MANAGERS = ADMINS

STATICFILES_DIRS = (
    'C:/server/web/static/',
)
STATIC_ROOT = 'C:/server/Apache2/htdocs/cdn/main/'
STATIC_URL = 'http://instancegaming.net:81/cdn/main/'

每当我更新控制台日志(例如,按回车键或执行 Ctrl+C。)时,控制台错误永远循环出现。

当我去canyouseeme.org,在服务器运行ning的80端口上,它说它可以看到服务。此外,我在端口 :81 上有一个干净的 Apache 2 服务器 运行ning,它在本地和远程都可以正常工作。此外,当我 运行 一个 python 脚本来简单地检查端口 80 时,它会给出与上面相同的(简化的)错误。

端口检查器脚本:

    import socket
s = socket.socket()
address = '127.0.0.1' # or 192.168.0.47
port = 80  # port number is a number, not string
try:
    s.connect((address, port)) 
    # originally, it was 
    # except Exception, e: 
    # but this syntax is not supported anymore. 
except Exception as e: 
    print("something's wrong with %s:%d. Exception is %s" % (address, port, e))
finally:
    s.close()

其中returns以下,

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

最后,我尝试用 Django 做一个干净的 env 希望它能改变一些东西,但是,一个全新的开箱即用的副本给出了完全相同的错误。

我最终很轻松地解决了这个问题。我原本以为它与 socket 80 有关,但经过深思熟虑后,我转 DEBUG = True 发现我缺少主目录模板,以及指向未知页面的链接。对于出现此错误的任何人,如果可以,请尝试打开 DEBUG

通过 python django --upgrade

重新安装 django

就我而言,我忘记设置电子邮件后端和身份验证。我通过将其添加到设置文件来解决它。

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

AUTHENTICATION_BACKENDS = (
    # Needed to login by username in Django admin, regardless of `allauth`
    "django.contrib.auth.backends.ModelBackend",

    # `allauth` specific authentication methods, such as login by e-mail
    "allauth.account.auth_backends.AuthenticationBackend",
)

就我而言,错误发生在我使用 django-allauth 且未配置电子邮件后端设置时。由于没有定义电子邮件后端,它使用 默认 SMTP 后端 试图向用户发送电子邮件。尽管没有 SMTP 设置,因此默认主机无法连接,因此我们收到此错误。这个上面的答案,这个人正在设置电子邮件后端的地方对我有用。虽然这个问题很普遍,但由于 allauth 包而不是 Django 或与服务器相关的问题本身,我遇到了错误。 你可以设置成console或者根据smtp。

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
AUTHENTICATION_BACKENDS = (
    # Needed to login by username in Django admin, regardless of `allauth`
    "django.contrib.auth.backends.ModelBackend",

    # `allauth` specific authentication methods, such as login by e-mail
    "allauth.account.auth_backends.AuthenticationBackend",
)

出现这种类型的错误,下面设置中没有设置,复制粘贴检查

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

是的,但更简单的方法是将其放入您的本地设置中:

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

然后所有电子邮件将打印在您的控制台中。