如何让python为每个会话创建一个新的类实例?
情况如下: 我有一个应用程序,其中包括一个用户登录功能 我的问题是: 当用户登录/尝试登录失败并创建用户对象时。对于一个用户,它符合以下预期行为:如何让python为每个会话创建一个新的类实例?,python,flask,scope,Python,Flask,Scope,情况如下: 我有一个应用程序,其中包括一个用户登录功能 我的问题是: 当用户登录/尝试登录失败并创建用户对象时。对于一个用户,它符合以下预期行为: 在未登录的情况下转到某个页面,并期望重定向到登录页面 提供不正确的登录信息,不要尝试第五次或第五次以上,除非重定向到登录页面 第五次或第五次以上给出的登录信息不正确,预期从任何尝试的路由重定向到致命登录错误消息,不接受进一步的登录尝试 给定的正确登录信息EXPECT内容对所有路由都可见 我试图解决的问题是,当一个用户登录时,会在所有用户会话的上下文中
class User:
def __init__(self,password,user_name)
self.password = some_password_hashing_method(password)
self.username = user_name
self.loggedin = False
self.passwordguesses = 0
这是评估登录请求的功能。它将首先检查是否存在用户对象(应以会话为基础),如果不存在,则根据登录请求实例化该对象,并通过使用的哈希算法对照哈希密码列表检查值
它只适用于一个用户,但问题是,当一个用户登录,然后另一个用户从另一台具有不同IP地址的计算机进入应用程序时,它不会创建新的用户对象。它将看到现有user.loggedin设置为True,并将用户视为在未登录时登录,另一个用户已登录
如何使Python将此变量视为实例变量,该变量将在每次创建新用户会话时生成?
@app.route('/verifylogin',methods = ['POST'])
def verifylogin():
checksPassword = g.readcsv('filewithpasswords.csv')
usersList = g.readcsv('filelistingusers.csv')
global user
try:
the_user.passwordguesses
except NameError:
user = User(request.form['userid'],request.form['password'])
i = 0
if user.password_guesses < 5:
while i < len(checksPassword):
if somehashcheckingmethod(checksPassword[i][0], request.form['password']) and usersList[i][0] == request.form['userid']:
user.loggedin = True
return redirect('/index')
i += 1
user.passwordguesses += 1
return redirect('/login')
else:
return render_template('fatal.html')
同样,解释此代码的上下文显然存在问题,因为它将一个用户的登录状态应用于所有后续用户会话
请注意,注释掉以下行并不能纠正此问题:
global user
注释掉后,这会将用户对象的范围更改为仅在声明它的函数verifylogin()的范围内
因此,如果我编写了一个新路由和一个用于呈现其内容的函数,那么现在对象“user”超出了我正在编写的用于呈现新路由内容的函数的范围:
@app.route('/index.html')
def index():
try:
user.isloggedin
except NameError:
return redirect('login')
if user.isloggedin != True: # this code and all code below it is unreachable, because you will always get a NameError exception from the above lines of code. This is not a duplicate.
return redirect('login')
return render_template('index.html')
这通常是通过在web上使用交付方式来实现的 会话是一个安全的(希望如此)cookie,您的应用程序将为每个客户端提供。你的应用程序应该能够生成一个持久的单独会话,该会话将一直持续到会话处于活动状态为止。对于许多流行的web框架,cookie包含的唯一内容是会话ID。通过这种方式,您可以为用户存储持久状态,并将其会话ID用作引用
@app.route('/index.html')
def index():
try:
user.isloggedin
except NameError:
return redirect('login')
if user.isloggedin != True: # this code and all code below it is unreachable, because you will always get a NameError exception from the above lines of code. This is not a duplicate.
return redirect('login')
return render_template('index.html')