App Engine:Handling Users

Google App Engine let's you take advantage of Google's user authorization framework and manage users easily. In most development environments, this can be an arduous task. For detailed info, see Google's User API

Using Config File to Specify Authorization

If you want to restrict your application so that only those with a Google account can use it, the simplest way is to add some code in your app.yaml configuration file. In the URL handler area, you specify:

        -  url: /.*
           script: controller.py
           login: required

When a page is requested that matches the url string (/.*), the handler will first check if the user is signed in to the application. If not, the user is redirected to the Google sign-in page. After signing in, the user will be redirected back to the application page.

Explicitly Managing Users

The app.yaml code makes enforcing a login real easy. You can also use Google's User API to explicitly handle things. For instance, the code below would perform authorization:
  # somewhere in file import users library
    from google.appengine.api import users

  # in handlers, explicitly check users
    class MainPage(webapp.RequestHandler):
          
def get(self):
          user = users.get_current_user() # see if user is logged in.
   
          if user:
                 # this is the normal case

   
         else:
                  self
.redirect(users.create_login_url(self.request.uri)) # call google sign in page
     # when you get here you have a logged in user
Note that the above is done automatically if you set login to 'required' in the app.yaml. Sometimes, though, you'll call users.get_current_user so you can personalize the site (e.g., saying 'Hello Dave', or showing just the user's data).

User-Specific Data
Many applications will keep data personalized to each user and/or keep a table of user preferences.
    class UserPrefs(db.Model):
            user = db.UserProperty()
            # other data specifying preferences
Many applications, especially web 2.0 apps, store user-specific data for many things other than just preferences. Thus, many tables will include a column for the user.

In-Class Worksheet
1. With Pencil and paper, answer the following:

Suppose we wanted to keep track of each user's games over time in Hangman?
  • What would our model look like?
  • How would we list the user's scores out?
  • How would we add a score after each game?
You may want to refer to the PersonBook sample as a refresher on persistent data.

2. Modify your hangman game to handle user scores.

Recent site activity