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.reques开发者_高级运维t.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.
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.
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))
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"
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.
精彩评论