如何将变量从类传递给 Django 中的每个对象的方法

问题描述

我正在使用 django 手动创建 OTP 身份验证器。我创建了一个创建 otp 并通过电子邮件将其发送给用户的类。我还没有编写发送电子邮件代码。我将通过 send_email() 内置函数完成它。请注意views.py中的代码,我想使用另一个函数来验证otp。但是一旦我在第二个函数中创建了相同的对象,它就会重新初始化变量。

def register(request):

""" Other stuffs like password matching goes here """
""" This will be provoked first in production """

     g=globals()
     g["user" + str(request.POST['username'])] = OTPclass()
     g["user" + str(request.POST['username'])].send_otp()

def verify(request):

""" This method will be provoked once the user enters the OTP received in the email """

    g=globals()

    g["user" + str(request.POST["username"])] = OTPclass() 
#In this part the value reinitializes to 0,but I must get the otp which was sent to the user

    if(int(request.POST['otp']) == g["user" + str(request.POST["username"])].the_otp):
        return redirect(login)
    else:
        print(g["user" + str(request.POST["username"])].the_otp)
        return HttpResponse("<html><body><h2>OTP mismatch</h2></body></html>")

class OTPclass:
    the_otp = 0
    def send_otp(self):
        self.the_otp = random.randint(1000,9999)
    """ send_email() will be used here to send the otp to the user """
    

请提出一种获取verify() 中发送给用户的值的方法。在 views.py 中全局声明变量会导致多个用户访问该函数时覆盖该值。

解决方法

我不喜欢 django,但我在使用 Flask 时遇到了同样的问题。 您可以使用会话将数据从一个请求保存到另一个请求。 https://docs.djangoproject.com/en/3.2/topics/http/sessions/

    # set password:
    request.session['one_time_password'] = 'secret'
    # check password:
    if request.session.get('one_time_password',False):
        if request.session['one_time_password'] == provided_password:
            # login

这可能是一种解决方案。

另一个想法是记住班级中的OTP。 (如果你不想使用数据库)

OTP = OTPclass()
def register(request):

""" Other stuffs like password matching goes here """
""" This will be provoked first in production """
    OTP.send_otp("user" + str(request.POST['username']))

def verify(request):

""" This method will be provoked once the user enters the OTP received in the email """
    if(OTP.check_otp("user" + str(request.POST["username"]),int(request.POST['otp']):
        return redirect(login)
    else:
        return HttpResponse("<html><body><h2>OTP mismatch</h2></body></html>")

class OTPclass:
    memo = {}
    
    def send_otp(self,user):
        self.memo[user] = random.randint(1000,9999)
    """ send_email() will be used here to send the otp to the user """

    def check_otp(self,user,password):
        if user in memo and memo[user] == password:
            return True
        else:
            return False

请记住,此解决方案仅适用于一个线程/进程。