Skip to main content
 首页 » 编程设计

python之IMAP4 不适用于 python anywhere 服务器,但相同的代码适用于本地主机

2025年02月15日37EasonJim

我想让用户使用我们学院的邮件服务器登录我的 django 网络应用程序。 但是此代码允许在本地主机上使用学院邮件登录,但不能在服务器上登录。

我试过 pythonanywhere django 提供的 shell:

from imaplib import IMAP4 
c = IMAP4('newmailhost.cc.iitk.ac.in') 

错误出现在 web 服务器中,但不是出现在本地主机 shell 中。

socket.gaierror: [Errno -2] Name or service not known 

在 mylib/backend.py 中

from django.contrib.auth.models import User 
from imaplib import IMAP4 
 
class MyCustomBackend: 
 
# Create an authentication method 
# This is called by the standard Django login procedure 
    def authenticate(self, username=None, password=None): 
        try: 
        # Check if this user is valid on the mail server 
            c = IMAP4('newmailhost.cc.iitk.ac.in') 
            c.login(username, password) 
        except: 
            return None 
 
        user, created = User.objects.get_or_create(username=username) 
 
        return user 
 
# Required for your backend to work properly - unchanged in most scenarios 
    def get_user(self, user_id): 
        try: 
            return User.objects.get(pk=user_id) 
        except User.DoesNotExist: 
            return None 

在 setting.py 中

AUTHENTICATION_BACKENDS = ( 
    'mylib.backend.MyCustomBackend', 
    'django.contrib.auth.backends.ModelBackend', 
 
) 

请您参考如下方法:

据我所知,该 DNS 名称未解析为地址。所以我的猜测是它是一个不存在于您的网络之外的私有(private)服务器。