Google App Engine重定向问题

时间:2010-12-03 20:53:31

标签: python google-app-engine google-cloud-datastore

我正在尝试制作用户验证脚本,如果密码和用户名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 个答案:

答案 0 :(得分: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")