1 .. _tutorials.gettingstarted.usingusers: 2 3 Using the Users Service 4 ======================= 5 Google App Engine provides several useful services based on Google 6 infrastructure, accessible by applications using libraries included with the 7 SDK. One such service is the Users service, which lets your application 8 integrate with Google user accounts. With the Users service, your users can 9 use the Google accounts they already have to sign in to your application. 10 Let's use the Users service to personalize this application's greeting. 11 12 13 Using Users 14 ----------- 15 Edit ``helloworld/helloworld.py`` again, and replace its contents with the 16 following:: 17 18 from google.appengine.api import users 19 import webapp2 20 21 class MainPage(webapp2.RequestHandler): 22 def get(self): 23 user = users.get_current_user() 24 25 if user: 26 self.response.headers['Content-Type'] = 'text/plain' 27 self.response.out.write('Hello, ' + user.nickname()) 28 else: 29 self.redirect(users.create_login_url(self.request.uri)) 30 31 application = webapp2.WSGIApplication([ 32 ('/', MainPage) 33 ], debug=True) 34 35 def main(): 36 application.run() 37 38 if __name__ == "__main__": 39 main() 40 41 Reload the page in your browser. Your application redirects you to the local 42 version of the Google sign-in page suitable for testing your application. 43 You can enter any username you'd like in this screen, and your application 44 will see a fake ``User`` object based on that username. 45 46 When your application is running on App Engine, users will be directed to the 47 Google Accounts sign-in page, then redirected back to your application after 48 successfully signing in or creating an account. 49 50 51 The Users API 52 ------------- 53 Let's take a closer look at the new pieces. 54 55 If the user is already signed in to your application, ``get_current_user()`` 56 returns the ``User`` object for the user. Otherwise, it returns ``None``:: 57 58 user = users.get_current_user() 59 60 If the user has signed in, display a personalized message, using the nickname 61 associated with the user's account:: 62 63 if user: 64 self.response.headers['Content-Type'] = 'text/plain' 65 self.response.out.write('Hello, ' + user.nickname()) 66 67 If the user has not signed in, tell ``webapp2`` to redirect the user's browser 68 to the Google account sign-in screen. The redirect includes the URL to this 69 page (``self.request.uri``) so the Google account sign-in mechanism will send 70 the user back here after the user has signed in or registered for a new 71 account:: 72 73 self.redirect(users.create_login_url(self.request.uri)) 74 75 For more information about the Users API, see the `Users reference <http://code.google.com/appengine/docs/python/users/>`_. 76 77 78 Next... 79 ------- 80 Our application can now greet visiting users by name. Let's add a feature that 81 will let users greet each other. 82 83 Continue to :ref:`tutorials.gettingstarted.handlingforms`. 84