delete
delete

Reputation:

How does this If conditional work in Python?

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class MainPage(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()

        if user:
            self.response.headers['Content-Type'] = 'text/plain'
            self.response.out.write('Hello, ' + user.nickname())
        else:
            self.redirect(users.create_login_url(self.request.uri))

application = webapp.WSGIApplication(
                                     [('/', MainPage)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

I don't understand how this line works:

    if user:
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Hello, ' + user.nickname())
    else:
        self.redirect(users.create_login_url(self.request.uri))

I'm guessing the users.get_current_user() return a boolean? Then, if that is the case how can it get a .nickname() method?

Thanks for the guidance.

Upvotes: 0

Views: 1272

Answers (4)

Colin
Colin

Reputation: 10820

It returns a user object, which could be None if there is no current user. None is kind of like the python equivalent of NULL, and it evaluates as false in a conditional.

Upvotes: 1

Elalfer
Elalfer

Reputation: 5338

users.get_current_user() returns user' object or None if the user is not logged in. It is possible in python to check if the variable value is None like:

a = None
if not a:
  print "a values is None"

Upvotes: 2

fmark
fmark

Reputation: 58577

I suspect that users.get_current_user() returns an object, or None if there is no current user. Python interprets None as False in a conditional statement.

Note that testing for None this way is a bad practise, however. Other things like an empty list [] also evaluate to False. Instead, the code should be modified to look like this:

    if user is not None:
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Hello, ' + user.nickname())
    else:
        self.redirect(users.create_login_url(self.request.uri))

Upvotes: 3

Adam Lear
Adam Lear

Reputation: 38768

It'll basically check if user is an actual object or None. If it's None, the code will go into the else block and redirect to a "create login" page.

Upvotes: 8

Related Questions