开发者

Google App Engine redirection problem

I'm trying to make a user verification script that redirects the user if the password and username cookies are empty or false. But no matter what I do it always sends the user to "/wrong2". It doesnt even bother checking the if. This is what the code looks like at the moment:

        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['u开发者_开发问答sername'], dictionary['password'])
        checkresult = checkq.get()
        if checkresult.username and checkresult.password is None:
            self.redirect("/wrong")
    else:
        self.redirect("/wrong2")

I'm very new to python and are trying to learn it and I just cant find where the fault is. Can anyone see where it is?


You're using hasattr to check to see if a dict contains a particular key, but you should be using the in operator instead. The hasattr function just checks to see if an object has a particular attribute.

So, you could instead write:

if 'username' in self.request.cookies and 'password' in self.request.cookies:
    # check against the datastore

But I think a slightly better approach would be this, which ensures that empty usernames or passwords (think username = '') don't get let in:

# 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")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜