oauth2client.appengine | index /usr/local/google/home/jcgregorio/projects/apiclient/oauth2client/appengine.py

`Utilities for Google App Engine
Utilities for making it easier to use OAuth 2.0 on Google App Engine.`

Modules
`` |  |
google.appengine.api.app_identity.app_identity base64 google.appengine.ext.db | httplib2 google.appengine.api.memcache pickle | simplejson time google.appengine.api.users | google.appengine.ext.webapp

Classes
`` |  | __builtin__.object OAuth2Decorator google.appengine.ext.db.Model(__builtin__.object) CredentialsModel google.appengine.ext.db.Property(__builtin__.object) CredentialsProperty FlowProperty google.appengine.ext.webapp.RequestHandler(__builtin__.object) OAuth2Handler oauth2client.client.AssertionCredentials(oauth2client.client.OAuth2Credentials) AppAssertionCredentials oauth2client.client.Storage(__builtin__.object) StorageByKeyName
class AppAssertionCredentials(oauth2client.client.AssertionCredentials)
`` | `Credentials object for App Engine Assertion Grants This object will allow an App Engine application to identify itself to Google and other OAuth 2.0 servers that can verify assertions. It can be used for the purpose of accessing data stored under an account assigned to the App Engine application itself. The algorithm used for generating the assertion is the Signed JSON Web Token (JWT) algorithm. Additional details can be found at the following link: http://self-issued.info/docs/draft-jones-json-web-token.html This credential does not require a flow to instantiate because it represents a two legged flow, and therefore has all of the required information to generate and refresh its own access tokens. AssertionFlowCredentials objects may be safely pickled and unpickled.`
| Method resolution order: AppAssertionCredentials oauth2client.client.AssertionCredentials oauth2client.client.OAuth2Credentials oauth2client.client.Credentials __builtin__.object Methods defined here: __init__(self, scope, audience='https://accounts.google.com/o/oauth2/token', assertion_type='http://oauth.net/grant_type/jwt/1.0/bearer', token_uri='https://accounts.google.com/o/oauth2/token', **kwargs) `Constructor for AppAssertionCredentials Args: scope: string, scope of the credentials being requested. audience: string, The audience, or verifier of the assertion. For convenience defaults to Google's audience. assertion_type: string, Type name that will identify the format of the assertion string. For convience, defaults to the JSON Web Token (JWT) assertion type string. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used.` Class methods defined here: from_json(cls, json) from __builtin__.type Methods inherited from oauth2client.client.OAuth2Credentials: __getstate__(self) `Trim the state down to something that can be pickled.` __setstate__(self, state) `Reconstitute the state of the object from being pickled.` authorize(self, http) `Authorize an httplib2.Http instance with these credentials. Args: http: An instance of httplib2.Http or something that acts like it. Returns: A modified instance of http that was passed in. Example: h = httplib2.Http() h = credentials.authorize(h) You can't create a new OAuth subclass of httplib2.Authenication because it never gets passed the absolute URI, which is needed for signing. So instead we have to overload 'request' with a closure that adds in the Authorization header and then calls the original version of 'request()'.` set_store(self, store) `Set the Storage for the credential. Args: store: Storage, an implementation of Stroage object. This is needed to store the latest access_token if it has expired and been refreshed. This implementation uses locking to check for updates before updating the access_token.` to_json(self) Data descriptors inherited from oauth2client.client.OAuth2Credentials: access_token_expired `True if the credential is expired or invalid. If the token_expiry isn't set, we assume the token doesn't expire.` Class methods inherited from oauth2client.client.Credentials: new_from_json(cls, s) from __builtin__.type `Utility class method to instantiate a Credentials subclass from a JSON representation produced by to_json(). Args: s: string, JSON from to_json(). Returns: An instance of the subclass of Credentials that was serialized with to_json().` Data descriptors inherited from oauth2client.client.Credentials: __dict__ `dictionary for instance variables (if defined)` __weakref__ `list of weak references to the object (if defined)` Data and other attributes inherited from oauth2client.client.Credentials: NON_SERIALIZED_MEMBERS = ['store']
class CredentialsModel(google.appengine.ext.db.Model)
`` | `Storage for OAuth 2.0 Credentials Storage of the model is keyed by the user.user_id().`
| Method resolution order: CredentialsModel google.appengine.ext.db.Model __builtin__.object Data descriptors defined here: credentials `App Engine datastore Property for Credentials. Utility property that allows easy storage and retrieval of oath2client.Credentials` Methods inherited from google.appengine.ext.db.Model: __init__(self, parent=None, key_name=None, _app=None, _from_entity=False, **kwds) `Creates a new instance of this model. To create a new entity, you instantiate a model and then call put(), which saves the entity to the datastore: person = Person() person.name = 'Bret' person.put() You can initialize properties in the model in the constructor with keyword arguments: person = Person(name='Bret') We initialize all other properties to the default value (as defined by the properties in the model definition) if they are not provided in the constructor. Args: parent: Parent instance for this instance or None, indicating a top- level instance. key_name: Name for new model instance. _from_entity: Intentionally undocumented. kwds: Keyword arguments mapping to properties of model. Also: key: Key instance for this instance, if provided makes parent and key_name redundant (they do not need to be set but if they are they must match the key).` delete(self, **kwargs) `Deletes this entity from the datastore. Args: config: datastore_rpc.Configuration to use for this request. Raises: TransactionFailedError if the data could not be committed.` dynamic_properties(self) `Returns a list of all dynamic properties defined for instance.` has_key(self) `Determine if this model instance has a complete key. When not using a fully self-assigned Key, ids are not assigned until the data is saved to the Datastore, but instances with a key name always have a full key. Returns: True if the object has been persisted to the datastore or has a key or has a key_name, otherwise False.` instance_properties(self) `Alias for dyanmic_properties.` is_saved(self) `Determine if entity is persisted in the datastore. New instances of Model do not start out saved in the data. Objects which are saved to or loaded from the Datastore will have a True saved state. Returns: True if object has been persisted to the datastore, otherwise False.` key(self) `Unique key for this entity. This property is only available if this entity is already stored in the datastore or if it has a full key, so it is available if this entity was fetched returned from a query, or after put() is called the first time for new entities, or if a complete key was given when constructed. Returns: Datastore key of persisted entity. Raises: NotSavedError when entity is not persistent.` parent(self) `Get the parent of the model instance. Returns: Parent of contained entity or parent provided in constructor, None if instance has no parent.` parent_key(self) `Get the parent's key. This method is useful for avoiding a potential fetch from the datastore but still get information about the instances parent. Returns: Parent key of entity, None if there is no parent.` put(self, **kwargs) `Writes this model instance to the datastore. If this instance is new, we add an entity to the datastore. Otherwise, we update this instance, and the key will remain the same. Args: config: datastore_rpc.Configuration to use for this request. Returns: The key of the instance (either the existing key or a new key). Raises: TransactionFailedError if the data could not be committed.` save = put(self, **kwargs) `Writes this model instance to the datastore. If this instance is new, we add an entity to the datastore. Otherwise, we update this instance, and the key will remain the same. Args: config: datastore_rpc.Configuration to use for this request. Returns: The key of the instance (either the existing key or a new key). Raises: TransactionFailedError if the data could not be committed.` to_xml(self, _entity_class=<class 'google.appengine.api.datastore.Entity'>) `Generate an XML representation of this model instance. atom and gd:namespace properties are converted to XML according to their respective schemas. For more information, see: http://www.atomenabled.org/developers/syndication/ http://code.google.com/apis/gdata/common-elements.html` Class methods inherited from google.appengine.ext.db.Model: all(cls, **kwds) from google.appengine.ext.db.PropertiedClass `Returns a query over all instances of this model from the datastore. Returns: Query that will retrieve all instances from entity collection.` entity_type(cls) from google.appengine.ext.db.PropertiedClass `Soon to be removed alias for kind.` fields(cls) from google.appengine.ext.db.PropertiedClass `Soon to be removed alias for properties.` from_entity(cls, entity) from google.appengine.ext.db.PropertiedClass `Converts the entity representation of this model to an instance. Converts datastore.Entity instance to an instance of cls. Args: entity: Entity loaded directly from datastore. Raises: KindError when cls is incorrect model for entity.` get(cls, keys, **kwargs) from google.appengine.ext.db.PropertiedClass `Fetch instance from the datastore of a specific Model type using key. We support Key objects and string keys (we convert them to Key objects automatically). Useful for ensuring that specific instance types are retrieved from the datastore. It also helps that the source code clearly indicates what kind of object is being retreived. Example: story = Story.get(story_key) Args: keys: Key within datastore entity collection to find; or string key; or list of Keys or string keys. config: datastore_rpc.Configuration to use for this request. Returns: If a single key was given: a Model instance associated with key for provided class if it exists in the datastore, otherwise None; if a list of keys was given: a list whose items are either a Model instance or None. Raises: KindError if any of the retreived objects are not instances of the type associated with call to 'get'.` get_by_id(cls, ids, parent=None, **kwargs) from google.appengine.ext.db.PropertiedClass `Get instance of Model class by id. Args: key_names: A single id or a list of ids. parent: Parent of instances to get. Can be a model or key. config: datastore_rpc.Configuration to use for this request.` get_by_key_name(cls, key_names, parent=None, **kwargs) from google.appengine.ext.db.PropertiedClass `Get instance of Model class by its key's name. Args: key_names: A single key-name or a list of key-names. parent: Parent of instances to get. Can be a model or key. config: datastore_rpc.Configuration to use for this request.` get_or_insert(cls, key_name, **kwds) from google.appengine.ext.db.PropertiedClass `Transactionally retrieve or create an instance of Model class. This acts much like the Python dictionary setdefault() method, where we first try to retrieve a Model instance with the given key name and parent. If it's not present, then we create a new instance (using the *kwds supplied) and insert that with the supplied key name. Subsequent calls to this method with the same key_name and parent will always yield the same entity (though not the same actual object instance), regardless of the *kwds supplied. If the specified entity has somehow been deleted separately, then the next call will create a new entity and return it. If the 'parent' keyword argument is supplied, it must be a Model instance. It will be used as the parent of the new instance of this Model class if one is created. This method is especially useful for having just one unique entity for a specific identifier. Insertion/retrieval is done transactionally, which guarantees uniqueness. Example usage: class WikiTopic(db.Model): creation_date = db.DatetimeProperty(auto_now_add=True) body = db.TextProperty(required=True) # The first time through we'll create the new topic. wiki_word = 'CommonIdioms' topic = WikiTopic.get_or_insert(wiki_word, body='This topic is totally new!') assert topic.key().name() == 'CommonIdioms' assert topic.body == 'This topic is totally new!' # The second time through will just retrieve the entity. overwrite_topic = WikiTopic.get_or_insert(wiki_word, body='A totally different message!') assert topic.key().name() == 'CommonIdioms' assert topic.body == 'This topic is totally new!' Args: key_name: Key name to retrieve or create. **kwds: Keyword arguments to pass to the constructor of the model class if an instance for the specified key name does not already exist. If an instance with the supplied key_name and parent already exists, the rest of these arguments will be discarded. Returns: Existing instance of Model class with the specified key_name and parent or a new one that has just been created. Raises: TransactionFailedError if the specified Model instance could not be retrieved or created transactionally (due to high contention, etc).` gql(cls, query_string, *args, **kwds) from google.appengine.ext.db.PropertiedClass `Returns a query using GQL query string. See appengine/ext/gql for more information about GQL. Args: query_string: properly formatted GQL query string with the 'SELECT * FROM <entity>' part omitted *args: rest of the positional arguments used to bind numeric references in the query. **kwds: dictionary-based arguments (for named parameters).` kind(cls) from google.appengine.ext.db.PropertiedClass `Returns the datastore kind we use for this model. We just use the name of the model for now, ignoring potential collisions.` properties(cls) from google.appengine.ext.db.PropertiedClass `Returns a dictionary of all the properties defined for this model.` Static methods inherited from google.appengine.ext.db.Model: __new__(*args, **unused_kwds) `Allow subclasses to call __new__() with arguments. Do NOT list 'cls' as the first argument, or in the case when the 'unused_kwds' dictionary contains the key 'cls', the function will complain about multiple argument values for 'cls'. Raises: TypeError if there are no positional arguments.` Data descriptors inherited from google.appengine.ext.db.Model: __dict__ `dictionary for instance variables (if defined)` __weakref__ `list of weak references to the object (if defined)` Data and other attributes inherited from google.appengine.ext.db.Model: __metaclass__ = <class 'google.appengine.ext.db.PropertiedClass'> `Meta-class for initializing Model classes properties. Used for initializing Properties defined in the context of a model. By using a meta-class much of the configuration of a Property descriptor becomes implicit. By using this meta-class, descriptors that are of class Model are notified about which class they belong to and what attribute they are associated with and can do appropriate initialization via __property_config__. Duplicate properties are not permitted.`
class CredentialsProperty(google.appengine.ext.db.Property)
`` | `App Engine datastore Property for Credentials. Utility property that allows easy storage and retrieval of oath2client.Credentials`
| Method resolution order: CredentialsProperty google.appengine.ext.db.Property __builtin__.object Methods defined here: empty(self, value) get_value_for_datastore(self, model_instance) `# For writing to datastore.` make_value_from_datastore(self, value) `# For reading from datastore.` validate(self, value) Data and other attributes defined here: data_type = <class 'oauth2client.client.Credentials'> `Base class for all Credentials objects. Subclasses must define an authorize() method that applies the credentials to an HTTP transport. Subclasses must also specify a classmethod named 'from_json' that takes a JSON string as input and returns an instaniated Crentials object.` Methods inherited from google.appengine.ext.db.Property: __get__(self, model_instance, model_class) `Returns the value for this property on the given model instance. See http://docs.python.org/ref/descriptors.html for a description of the arguments to this class and what they mean.` __init__(self, verbose_name=None, name=None, default=None, required=False, validator=None, choices=None, indexed=True) `Initializes this Property with the given options. Args: verbose_name: User friendly name of property. name: Storage name for property. By default, uses attribute name as it is assigned in the Model sub-class. default: Default value for property if none is assigned. required: Whether property is required. validator: User provided method used for validation. choices: User provided set of valid property values. indexed: Whether property is indexed.` __property_config__(self, model_class, property_name) `Configure property, connecting it to its model. Configure the property so that it knows its property name and what class it belongs to. Args: model_class: Model class which Property will belong to. property_name: Name of property within Model instance to store property values in. By default this will be the property name preceded by an underscore, but may change for different subclasses.` __set__(self, model_instance, value) `Sets the value for this property on the given model instance. See http://docs.python.org/ref/descriptors.html for a description of the arguments to this class and what they mean.` datastore_type(self) `Deprecated backwards-compatible accessor method for self.data_type.` default_value(self) `Default value for unassigned values. Returns: Default value as provided by __init__(default).` Data descriptors inherited from google.appengine.ext.db.Property: __dict__ `dictionary for instance variables (if defined)` __weakref__ `list of weak references to the object (if defined)` Data and other attributes inherited from google.appengine.ext.db.Property: creation_counter = 1
class FlowProperty(google.appengine.ext.db.Property)
`` | `App Engine datastore Property for Flow. Utility property that allows easy storage and retreival of an oauth2client.Flow`
| Method resolution order: FlowProperty google.appengine.ext.db.Property __builtin__.object Methods defined here: empty(self, value) get_value_for_datastore(self, model_instance) `# For writing to datastore.` make_value_from_datastore(self, value) `# For reading from datastore.` validate(self, value) Data and other attributes defined here: data_type = <class 'oauth2client.client.Flow'> `Base class for all Flow objects.` Methods inherited from google.appengine.ext.db.Property: __get__(self, model_instance, model_class) `Returns the value for this property on the given model instance. See http://docs.python.org/ref/descriptors.html for a description of the arguments to this class and what they mean.` __init__(self, verbose_name=None, name=None, default=None, required=False, validator=None, choices=None, indexed=True) `Initializes this Property with the given options. Args: verbose_name: User friendly name of property. name: Storage name for property. By default, uses attribute name as it is assigned in the Model sub-class. default: Default value for property if none is assigned. required: Whether property is required. validator: User provided method used for validation. choices: User provided set of valid property values. indexed: Whether property is indexed.` __property_config__(self, model_class, property_name) `Configure property, connecting it to its model. Configure the property so that it knows its property name and what class it belongs to. Args: model_class: Model class which Property will belong to. property_name: Name of property within Model instance to store property values in. By default this will be the property name preceded by an underscore, but may change for different subclasses.` __set__(self, model_instance, value) `Sets the value for this property on the given model instance. See http://docs.python.org/ref/descriptors.html for a description of the arguments to this class and what they mean.` datastore_type(self) `Deprecated backwards-compatible accessor method for self.data_type.` default_value(self) `Default value for unassigned values. Returns: Default value as provided by __init__(default).` Data descriptors inherited from google.appengine.ext.db.Property: __dict__ `dictionary for instance variables (if defined)` __weakref__ `list of weak references to the object (if defined)` Data and other attributes inherited from google.appengine.ext.db.Property: creation_counter = 1
class OAuth2Decorator(__builtin__.object)
`` | `Utility for making OAuth 2.0 easier. Instantiate and then use with oauth_required or oauth_aware as decorators on webapp.RequestHandler methods. Example: decorator = OAuth2Decorator( client_id='837...ent.com', client_secret='Qh...wwI', scope='https://www.googleapis.com/auth/buzz') class MainHandler(webapp.RequestHandler): @decorator.oauth_required def get(self): http = decorator.http() # http is authorized with the user's Credentials and can be used # in API calls`
| Methods defined here: __init__(self, client_id, client_secret, scope, auth_uri='https://accounts.google.com/o/oauth2/auth', token_uri='https://accounts.google.com/o/oauth2/token') `Constructor for OAuth2Decorator Args: client_id: string, client identifier. client_secret: string client secret. scope: string, scope of the credentials being requested. auth_uri: string, URI for authorization endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used.` authorize_url(self) `Returns the URL to start the OAuth dance. Must only be called from with a webapp.RequestHandler subclassed method that had been decorated with either @oauth_required or @oauth_aware.` has_credentials(self) `True if for the logged in user there are valid access Credentials. Must only be called from with a webapp.RequestHandler subclassed method that had been decorated with either @oauth_required or @oauth_aware.` http(self) `Returns an authorized http instance. Must only be called from within an @oauth_required decorated method, or from within an @oauth_aware decorated method where has_credentials() returns True.` oauth_aware(self, method) `Decorator that sets up for OAuth 2.0 dance, but doesn't do it. Does all the setup for the OAuth dance, but doesn't initiate it. This decorator is useful if you want to create a page that knows whether or not the user has granted access to this application. From within a method decorated with @oauth_aware the has_credentials() and authorize_url() methods can be called. Args: method: callable, to be decorated method of a webapp.RequestHandler instance.` oauth_required(self, method) `Decorator that starts the OAuth 2.0 dance. Starts the OAuth dance for the logged in user if they haven't already granted access for this application. Args: method: callable, to be decorated method of a webapp.RequestHandler instance.` Data descriptors defined here: __dict__ `dictionary for instance variables (if defined)` __weakref__ `list of weak references to the object (if defined)`
class OAuth2Handler(google.appengine.ext.webapp.RequestHandler)
`` | `Handler for the redirect_uri of the OAuth 2.0 dance.`
| Method resolution order: OAuth2Handler google.appengine.ext.webapp.RequestHandler __builtin__.object Methods defined here: get = check_login(self, *args) Methods inherited from google.appengine.ext.webapp.RequestHandler: delete(self, *args) `Handler method for DELETE requests.` error(self, code) `Clears the response output stream and sets the given HTTP error code. Args: code: the HTTP status error code (e.g., 501)` handle_exception(self, exception, debug_mode) `Called if this handler throws an exception during execution. The default behavior is to call error(500) and print a stack trace if debug_mode is True. Args: exception: the exception that was thrown debug_mode: True if the web application is running in debug mode` head(self, *args) `Handler method for HEAD requests.` initialize(self, request, response) `Initializes this request handler with the given Request and Response.` options(self, *args) `Handler method for OPTIONS requests.` post(self, *args) `Handler method for POST requests.` put(self, *args) `Handler method for PUT requests.` redirect(self, uri, permanent=False) `Issues an HTTP redirect to the given relative URL. Args: uri: a relative or absolute URI (e.g., '../flowers.html') permanent: if true, we use a 301 redirect instead of a 302 redirect` trace(self, *args) `Handler method for TRACE requests.` Class methods inherited from google.appengine.ext.webapp.RequestHandler: get_url(cls, *args, **kargs) from __builtin__.type `Returns the url for the given handler. The default implementation uses the patterns passed to the active WSGIApplication to create a url. However, it is different from Django's urlresolvers.reverse() in the following ways: - It does not try to resolve handlers via module loading - It does not support named arguments - It performs some post-prosessing on the url to remove some regex operators. - It will try to fill in the left-most missing arguments with the args used in the active request. Args: args: Parameters for the url pattern's groups. kwargs: Optionally contains 'implicit_args' that can either be a boolean or a tuple. When it is True, it will use the arguments to the active request as implicit arguments. When it is False (default), it will not use any implicit arguments. When it is a tuple, it will use the tuple as the implicit arguments. the left-most args if some are missing from args. Returns: The url for this handler/args combination. Raises: NoUrlFoundError: No url pattern for this handler has the same number of args that were passed in.` new_factory(cls, *args, **kwargs) from __builtin__.type `Create new request handler factory. Use factory method to create reusable request handlers that just require a few configuration parameters to construct. Also useful for injecting shared state between multiple request handler instances without relying on global variables. For example, to create a set of post handlers that will do simple text transformations you can write: class ChangeTextHandler(webapp.RequestHandler): def __init__(self, transform): self.transform = transform def post(self): response_text = transform( self.request.request.body_file.getvalue()) self.response.out.write(response_text) application = webapp.WSGIApplication( [('/to_lower', ChangeTextHandler.new_factory(str.lower)), ('/to_upper', ChangeTextHandler.new_factory(str.upper)), ], debug=True) Text POSTed to /to_lower will be lower cased. Text POSTed to /to_upper will be upper cased.` Data descriptors inherited from google.appengine.ext.webapp.RequestHandler: __dict__ `dictionary for instance variables (if defined)` __weakref__ `list of weak references to the object (if defined)`
class StorageByKeyName(oauth2client.client.Storage)
`` | `Store and retrieve a single credential to and from the App Engine datastore. This Storage helper presumes the Credentials have been stored as a CredenialsProperty on a datastore model class, and that entities are stored by key_name.`
| Method resolution order: StorageByKeyName oauth2client.client.Storage __builtin__.object Methods defined here: __init__(self, model, key_name, property_name, cache=None) `Constructor for Storage. Args: model: db.Model, model class key_name: string, key name for the entity that has the credentials property_name: string, name of the property that is a CredentialsProperty cache: memcache, a write-through cache to put in front of the datastore` get(self) `Retrieve Credential from datastore. Returns: oauth2client.Credentials` put(self, credentials) `Write a Credentials to the datastore. Args: credentials: Credentials, the credentials to store.` Methods inherited from oauth2client.client.Storage: acquire_lock(self) `Acquires any lock necessary to access this Storage. This lock is not reentrant.` locked_get(self) `Retrieve credential. The Storage lock must be held when this is called. Returns: oauth2client.client.Credentials` locked_put(self, credentials) `Write a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store.` release_lock(self) `Release the Storage lock. Trying to release a lock that isn't held will result in a RuntimeError.` Data descriptors inherited from oauth2client.client.Storage: __dict__ `dictionary for instance variables (if defined)` __weakref__ `list of weak references to the object (if defined)`

Functions
`` |  | main()

Data
`` |  | OAUTH2CLIENT_NAMESPACE = 'oauth2client#ns' __author__ = 'jcgregorio@google.com (Joe Gregorio)' application = <google.appengine.ext.webapp.WSGIApplication object>

Author
`` |  | jcgregorio@google.com (Joe Gregorio)