Django Python - 无法建立连接,因为目标机器主动拒绝它

Posted

技术标签:

【中文标题】Django Python - 无法建立连接,因为目标机器主动拒绝它【英文标题】:Django Python - No connection could be made because the target machine actively refused it 【发布时间】:2017-05-13 08:27:15 【问题描述】:

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

我看过其他类似的帖子 (Python Django-Helpdesk Error: No connection could be made because the target machine actively refused it) 和其他一些帖子,但这些帖子似乎都不能解决问题。

控制台窗口:

(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/'

只要我更新控制台日志(例如,按 Enter 或执行Ctrl+C),控制台错误就会永远循环。

当我访问 canyouseeme.org 时,在服务器运行的端口 80 上,它说 它可以看到该服务。此外,我有一个干净的 Apache 2 服务器在端口 :81 上运行,它在本地和远程都可以正常工作。此外,当我运行 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()

返回以下内容,

[WinError 10061] 目标机器主动拒绝,无法连接

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

【问题讨论】:

您是在另一台机器上运行服务器,还是在您连接的机器上运行? 您的服务器在192.168.0.47 上运行,因此您不能在脚本中使用127.0.0.1 @furas 是正确的。尝试使用python manage.py runserver 0.0.0.0:80 运行开发服务器。 看来我用什么ip都无所谓,结果都是一样的。另外,我尝试从我的网络外部访问我的网站,这在过去运行良好,但我得到了超时。我也尝试过重置我的路由器和所有子集线器。 我可能完全错了,但这可能是类似于 DDos 的东西,还是只会破坏我的整个网络?另外,我会尝试重新安装 Python。 【参考方案1】:

我最终很容易解决了这个问题。本来以为和socket 80有关系,但经过深思熟虑,转了DEBUG = True,发现我的home目录少了一个模板,还有到未知页面的链接。对于遇到此错误的任何人,如果可以,请尝试打开DEBUG

【讨论】:

好点,我遇到了同样的问题,这是由于缺少 EMAIL_BACKEND 造成的。【参考方案2】:

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

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

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

【讨论】:

这并没有提供问题的答案。一旦你有足够的reputation,你就可以comment on any post;相反,provide answers that don't require clarification from the asker。 - From Review【参考方案3】:

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

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

【讨论】:

【参考方案4】:

通过 python django --upgrade 重新安装 django

【讨论】:

虽然这可能会解除对提问者的阻止,但这个答案并没有真正解决问题的根源,也没有解释为什么需要重新安装,或者认为有一个解决方案不涉及“关闭它并重新开启。”【参考方案5】:

在我的情况下,我忘记设置电子邮件后端和身份验证。我通过将它添加到设置文件来解决它。

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

【讨论】:

【参考方案6】:

在我的情况下,当我使用 django-allauth 而不配置电子邮件后端设置时发生错误。由于没有定义电子邮件后端,它使用 默认 SMTP 后端 尝试向用户发送电子邮件。虽然没有 SMTP 设置,因此默认主机无法连接,因此我们收到此错误。上面这个人设置电子邮件后端的答案确实对我有用。尽管问题很笼统,但由于 allauth 包而不是 Django 或与服务器相关的问题本身,我遇到了错误。 可以设置为控制台,也可以根据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",
)

【讨论】:

以上是关于Django Python - 无法建立连接,因为目标机器主动拒绝它的主要内容,如果未能解决你的问题,请参考以下文章

DJANGO EMAIL CONFIRMATION: [WinError 10061] 由于目标机器主动拒绝,无法建立连接

无法使用 Django channels_redis 与 Heroku Redis 建立连接

python Django1.3 建立网站,无法加载css

python 如何建立socket长连接

.NET 4 新的 TCP 客户端无法连接:无法建立连接,因为目标机器主动拒绝它

连接被对方​​拒绝:10061:无法建立连接,因为目标机器主动拒绝它