English | Site Directory

User Objects

An instance of the User class represents a user. User instances are unique and comparable. If two instances are equal, then they represent the same user.

The application can access the User instance for the current user by calling the users.get_current_user() function.

from google.appengine.api import users

user = users.get_current_user()
if not user:
  # The user is not signed in.
else:
  print "Hello, %s!" % user.nickname()

A User instance can be also constructed from an email address.

user = users.User("Albert.Johnson@example.com")

If the User constructor is called with an email address that does not correspond with a valid Google account, the object will be created but it will not correspond with a real Google account. This will be the case even if someone creates a Google account with the given email address after the object is stored. A User value with an email address that does not represent a Google account at the time it is created will never match a User value that represents a real user.

When running under the development web server, all User objects are assumed to represent valid Google accounts when stored in the (simulated) datastore.

Using User Values With the Datastore

User instances can be datastore property values.

class UserPrefs(db.Model):
  user = db.UserProperty()

user = users.get_current_user()
if user:
  q = db.GqlQuery("SELECT * FROM UserPrefs WHERE user = :1", user)
  userprefs = q.get()

Note: At this time, the users API does not provide permanent unique identifiers for Google Accounts. While an email address is unique to an account at a given moment, the user can change the email address for the account at any time. Changes to email addresses are not propagated to datastore User values automatically. Unique user IDs and email address change propagation may be implemented in a future release. Until either of these features is implemented, there is no good way to associate the current user with the user's preferences data after an email address change.

Avoid using the user's email address in a datastore entity key name. If your application stores user preferences data, consider using a User property and a query to retrieve the data. This technique will automatically work with email address changes after the propagation feature is implemented. It does not prevent the accidental creation of multiple preferences objects (which would require a calculable key name and a transaction), but the query will always return the correct result due to ordering.