Google App Engine 重定向问题
我正在尝试写一个用户验证的脚本,如果用户名和密码的cookie是空的或者是错误的,就把用户重定向到另一个页面。但是无论我怎么做,用户总是被送到"/wrong2"这个页面。代码根本没有检查条件。这是我目前的代码:
dictionary = self.request.str_cookies
if hasattr(dictionary, 'password') and hasattr(dictionary, 'username'):
checkq = db.GqlQuery("SELECT * FROM Users WHERE username = :1 AND password = :2", dictionary['username'], dictionary['password'])
checkresult = checkq.get()
if checkresult.username and checkresult.password is None:
self.redirect("/wrong")
else:
self.redirect("/wrong2")
我对Python非常陌生,正在努力学习,但就是找不到问题出在哪里。有没有人能帮我看看?
1 个回答
2
你在用 hasattr
来检查一个 dict
里是否有某个特定的键,但其实应该用 in
操作符。因为 hasattr
这个函数只是用来检查一个对象是否有某个特定的属性。
所以,你可以这样写:
if 'username' in self.request.cookies and 'password' in self.request.cookies:
# check against the datastore
不过,我觉得有个稍微更好的方法,就是确保空的用户名或密码(比如 username = ''
)不会被允许通过:
# will be None if the cookie is missing
username = self.request.cookies.get('username')
password = self.request.cookies.get('password')
# This makes sure that a username and password were both retrieved
# from the cookies, and that they're both NOT the empty string (because
# the empty string evaluates to False in this context)
if username and password:
# check against the datastore
else:
self.redirect("/wrong2")