desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Get pretty printed object prototype from the schema name. Args: name: string, Name of schema in the discovery document. Returns: string, A string that contains a prototype object with comments that conforms to the given schema.'
def prettyPrintByName(self, name):
return self._prettyPrintByName(name, seen=[], dent=1)[:(-2)]
'Get pretty printed object prototype of schema. Args: schema: object, Parsed JSON schema. seen: list of string, Names of schema already seen. Used to handle recursive definitions. Returns: string, A string that contains a prototype object with comments that conforms to the given schema.'
def _prettyPrintSchema(self, schema, seen=None, dent=0):
if (seen is None): seen = [] return _SchemaToStruct(schema, seen, dent).to_str(self._prettyPrintByName)
'Get pretty printed object prototype of schema. Args: schema: object, Parsed JSON schema. Returns: string, A string that contains a prototype object with comments that conforms to the given schema.'
def prettyPrintSchema(self, schema):
return self._prettyPrintSchema(schema, dent=1)[:(-2)]
'Get deserialized JSON schema from the schema name. Args: name: string, Schema name.'
def get(self, name):
return self.schemas[name]
'Constructor. Args: schema: object, Parsed JSON schema. seen: list, List of names of schema already seen while parsing. Used to handle recursive definitions. dent: int, Initial indentation depth.'
def __init__(self, schema, seen, dent=0):
self.value = [] self.string = None self.schema = schema self.dent = dent self.from_cache = None self.seen = seen
'Add text as a line to the output. Args: text: string, Text to output.'
def emit(self, text):
self.value.extend([(' ' * self.dent), text, '\n'])
'Add text to the output, but with no line terminator. Args: text: string, Text to output.'
def emitBegin(self, text):
self.value.extend([(' ' * self.dent), text])
'Add text and comment to the output with line terminator. Args: text: string, Text to output. comment: string, Python comment.'
def emitEnd(self, text, comment):
if comment: divider = (('\n' + (' ' * (self.dent + 2))) + '# ') lines = comment.splitlines() lines = [x.rstrip() for x in lines] comment = divider.join(lines) self.value.extend([text, ' # ', comment, '\n']) else: self.value.extend([text, '\n'])
'Increase indentation level.'
def indent(self):
self.dent += 1
'Decrease indentation level.'
def undent(self):
self.dent -= 1
'Prototype object based on the schema, in Python code with comments. Args: schema: object, Parsed JSON schema file. Returns: Prototype object based on the schema, in Python code with comments.'
def _to_str_impl(self, schema):
stype = schema.get('type') if (stype == 'object'): self.emitEnd('{', schema.get('description', '')) self.indent() for (pname, pschema) in schema.get('properties', {}).iteritems(): self.emitBegin(('"%s": ' % pname)) self._to_str_impl(pschema) self.undent...
'Prototype object based on the schema, in Python code with comments. Args: from_cache: callable(name, seen), Callable that retrieves an object prototype for a schema with the given name. Seen is a list of schema names already seen as we recursively descend the schema definition. Returns: Prototype object based on the s...
def to_str(self, from_cache):
self.from_cache = from_cache return self._to_str_impl(self.schema)
'Constructor. Args: resumable_progress: int, bytes sent so far. total_size: int, total bytes in complete upload.'
def __init__(self, resumable_progress, total_size):
self.resumable_progress = resumable_progress self.total_size = total_size
'Percent of upload completed, as a float.'
def progress(self):
return (float(self.resumable_progress) / float(self.total_size))
'Utility function for creating a JSON representation of a MediaUpload. Args: strip: array, An array of names of members to not include in the JSON. Returns: string, a JSON representation of this instance, suitable to pass to from_json().'
def _to_json(self, strip=None):
t = type(self) d = copy.copy(self.__dict__) if (strip is not None): for member in strip: del d[member] d['_class'] = t.__name__ d['_module'] = t.__module__ return simplejson.dumps(d)
'Create a JSON representation of an instance of MediaUpload. Returns: string, a JSON representation of this instance, suitable to pass to from_json().'
def to_json(self):
return self._to_json()
'Utility class method to instantiate a MediaUpload subclass from a JSON representation produced by to_json(). Args: s: string, JSON from to_json(). Returns: An instance of the subclass of MediaUpload that was serialized with to_json().'
@classmethod def new_from_json(cls, s):
data = simplejson.loads(s) module = data['_module'] m = __import__(module, fromlist=module.split('.')[:(-1)]) kls = getattr(m, data['_class']) from_json = getattr(kls, 'from_json') return from_json(s)
'Constructor. Args: filename: string, Name of the file. mimetype: string, Mime-type of the file. If None then a mime-type will be guessed from the file extension. chunksize: int, File will be uploaded in chunks of this many bytes. Only used if resumable=True. resumable: bool, True if this is a resumable upload. False m...
def __init__(self, filename, mimetype=None, chunksize=(256 * 1024), resumable=False):
self._filename = filename self._size = os.path.getsize(filename) self._fd = None if (mimetype is None): (mimetype, encoding) = mimetypes.guess_type(filename) self._mimetype = mimetype self._chunksize = chunksize self._resumable = resumable
'Get bytes from the media. Args: begin: int, offset from beginning of file. length: int, number of bytes to read, starting at begin. Returns: A string of bytes read. May be shorted than length if EOF was reached first.'
def getbytes(self, begin, length):
if (self._fd is None): self._fd = open(self._filename, 'rb') self._fd.seek(begin) return self._fd.read(length)
'Creating a JSON representation of an instance of Credentials. Returns: string, a JSON representation of this instance, suitable to pass to from_json().'
def to_json(self):
return self._to_json(['_fd'])
'Constructor for an HttpRequest. Args: http: httplib2.Http, the transport object to use to make a request postproc: callable, called on the HTTP response and content to transform it into a data object before returning, or raising an exception on an error. uri: string, the absolute URI to send the request to method: str...
def __init__(self, http, postproc, uri, method='GET', body=None, headers=None, methodId=None, resumable=None):
self.uri = uri self.method = method self.body = body self.headers = (headers or {}) self.methodId = methodId self.http = http self.postproc = postproc self.resumable = resumable (major, minor, params) = mimeparse.parse_mime_type(headers.get('content-type', 'application/json')) se...
'Execute the request. Args: http: httplib2.Http, an http object to be used in place of the one the HttpRequest request object was constructed with. Returns: A deserialized object model of the response body as determined by the postproc. Raises: apiclient.errors.HttpError if the response was not a 2xx. httplib2.Error if...
def execute(self, http=None):
if (http is None): http = self.http if self.resumable: body = None while (body is None): (_, body) = self.next_chunk(http) return body else: (resp, content) = http.request(self.uri, self.method, body=self.body, headers=self.headers) if (resp.status...
'Execute the next step of a resumable upload. Can only be used if the method being executed supports media uploads and the MediaUpload object passed in was flagged as using resumable upload. Example: media = MediaFileUpload(\'smiley.png\', mimetype=\'image/png\', chunksize=1000, resumable=True) request = service.object...
def next_chunk(self, http=None):
if (http is None): http = self.http if (self.resumable_uri is None): start_headers = copy.copy(self.headers) start_headers['X-Upload-Content-Type'] = self.resumable.mimetype() start_headers['X-Upload-Content-Length'] = str(self.resumable.size()) start_headers['content-len...
'Returns a JSON representation of the HttpRequest.'
def to_json(self):
d = copy.copy(self.__dict__) if (d['resumable'] is not None): d['resumable'] = self.resumable.to_json() del d['http'] del d['postproc'] return simplejson.dumps(d)
'Returns an HttpRequest populated with info from a JSON object.'
@staticmethod def from_json(s, http, postproc):
d = simplejson.loads(s) if (d['resumable'] is not None): d['resumable'] = MediaUpload.new_from_json(d['resumable']) return HttpRequest(http, postproc, uri=d['uri'], method=d['method'], body=d['body'], headers=d['headers'], methodId=d['methodId'], resumable=d['resumable'])
'Constructor for a BatchHttpRequest. Args: callback: callable, A callback to be called for each response, of the form callback(id, response). The first parameter is the request id, and the second is the deserialized response object. batch_uri: string, URI to send batch requests to.'
def __init__(self, callback=None, batch_uri=None):
if (batch_uri is None): batch_uri = 'https://www.googleapis.com/batch' self._batch_uri = batch_uri self._callback = callback self._requests = {} self._order = [] self._last_auto_id = 0 self._base_id = None
'Convert an id to a Content-ID header value. Args: id_: string, identifier of individual request. Returns: A Content-ID header with the id_ encoded into it. A UUID is prepended to the value because Content-ID headers are supposed to be universally unique.'
def _id_to_header(self, id_):
if (self._base_id is None): self._base_id = uuid.uuid4() return ('<%s+%s>' % (self._base_id, urllib.quote(id_)))
'Convert a Content-ID header value to an id. Presumes the Content-ID header conforms to the format that _id_to_header() returns. Args: header: string, Content-ID header value. Returns: The extracted id value. Raises: BatchError if the header is not in the expected format.'
def _header_to_id(self, header):
if ((header[0] != '<') or (header[(-1)] != '>')): raise BatchError(('Invalid value for Content-ID: %s' % header)) if ('+' not in header): raise BatchError(('Invalid value for Content-ID: %s' % header)) (base, id_) = header[1:(-1)].rsplit('+', 1) return urllib.unqu...
'Convert an HttpRequest object into a string. Args: request: HttpRequest, the request to serialize. Returns: The request as a string in application/http format.'
def _serialize_request(self, request):
parsed = urlparse.urlparse(request.uri) request_line = urlparse.urlunparse((None, None, parsed.path, parsed.params, parsed.query, None)) status_line = (((request.method + ' ') + request_line) + ' HTTP/1.1\n') (major, minor) = request.headers.get('content-type', 'application/json').split('/') m...
'Convert string into httplib2 response and content. Args: payload: string, headers and body as a string. Returns: A pair (resp, content) like would be returned from httplib2.request.'
def _deserialize_response(self, payload):
(status_line, payload) = payload.split('\n', 1) (protocol, status, reason) = status_line.split(' ', 2) parser = FeedParser() parser.feed(payload) msg = parser.close() msg['status'] = status resp = httplib2.Response(msg) resp.reason = reason resp.version = int(protocol.split('/', 1...
'Create a new id. Auto incrementing number that avoids conflicts with ids already used. Returns: string, a new unique id.'
def _new_id(self):
self._last_auto_id += 1 while (str(self._last_auto_id) in self._requests): self._last_auto_id += 1 return str(self._last_auto_id)
'Add a new request. Every callback added will be paired with a unique id, the request_id. That unique id will be passed back to the callback when the response comes back from the server. The default behavior is to have the library generate it\'s own unique id. If the caller passes in a request_id then they must ensure ...
def add(self, request, callback=None, request_id=None):
if (request_id is None): request_id = self._new_id() if (request.resumable is not None): raise BatchError('Resumable requests cannot be used in a batch request.') if (request_id in self._requests): raise KeyError(('A request with this ID already...
'Execute all the requests as a single batched HTTP request. Args: http: httplib2.Http, an http object to be used in place of the one the HttpRequest request object was constructed with. If one isn\'t supplied then use a http object from the requests in this batch. Returns: None Raises: apiclient.errors.HttpError if th...
def execute(self, http=None):
if (http is None): for request_id in self._order: (request, callback) = self._requests[request_id] if (request is not None): http = request.http break if (http is None): raise ValueError('Missing a valid http object.') msgRo...
'Constructor for HttpRequestMock Args: resp: httplib2.Response, the response to emulate coming from the request content: string, the response body postproc: callable, the post processing function usually supplied by the model class. See model.JsonModel.response() as an example.'
def __init__(self, resp, content, postproc):
self.resp = resp self.content = content self.postproc = postproc if (resp is None): self.resp = httplib2.Response({'status': 200, 'reason': 'OK'}) if ('reason' in self.resp): self.resp.reason = self.resp['reason']
'Execute the request. Same behavior as HttpRequest.execute(), but the response is mocked and not really from an HTTP request/response.'
def execute(self, http=None):
return self.postproc(self.resp, self.content)
'Constructor for RequestMockBuilder The constructed object should be a callable object that can replace the class HttpResponse. responses - A dictionary that maps methodIds into tuples of (httplib2.Response, content). The methodId comes from the \'rpcName\' field in the discovery document. check_unexpected - A boolean ...
def __init__(self, responses, check_unexpected=False):
self.responses = responses self.check_unexpected = check_unexpected
'Implements the callable interface that discovery.build() expects of requestBuilder, which is to build an object compatible with HttpRequest.execute(). See that method for the description of the parameters and the expected response.'
def __call__(self, http, postproc, uri, method='GET', body=None, headers=None, methodId=None, resumable=None):
if (methodId in self.responses): response = self.responses[methodId] (resp, content) = response[:2] if (len(response) > 2): expected_body = response[2] if (bool(expected_body) != bool(body)): raise UnexpectedBodyError(expected_body, body) i...
'Args: filename: string, absolute filename to read response from headers: dict, header to return with response'
def __init__(self, filename, headers=None):
if (headers is None): headers = {'status': '200 OK'} f = file(filename, 'r') self.data = f.read() f.close() self.headers = headers
'Args: iterable: iterable, a sequence of pairs of (headers, body)'
def __init__(self, iterable):
self._iterable = iterable
'Constructor for Storage. Args: model: db.Model, model class key_name: string, key name for the entity that has the credentials key_value: string, key value for the entity that has the credentials property_name: string, name of the property that is an CredentialsProperty'
def __init__(self, model_class, key_name, key_value, property_name):
self.model_class = model_class self.key_name = key_name self.key_value = key_value self.property_name = property_name
'Retrieve Credential from datastore. Returns: oauth2client.Credentials'
def locked_get(self):
credential = None query = {self.key_name: self.key_value} entities = self.model_class.objects.filter(**query) if (len(entities) > 0): credential = getattr(entities[0], self.property_name) if (credential and hasattr(credential, 'set_store')): credential.set_store(self) ret...
'Write a Credentials to the datastore. Args: credentials: Credentials, the credentials to store.'
def locked_put(self, credentials):
args = {self.key_name: self.key_value} entity = self.model_class(**args) setattr(entity, self.property_name, credentials) entity.save()
'Take an httplib2.Http instance (or equivalent) and authorizes it for the set of credentials, usually by replacing http.request() with a method that adds in the appropriate headers and then delegates to the original Http.request() method.'
def authorize(self, http):
_abstract()
'Utility function for creating a JSON representation of an instance of Credentials. Args: strip: array, An array of names of members to not include in the JSON. Returns: string, a JSON representation of this instance, suitable to pass to from_json().'
def _to_json(self, strip):
t = type(self) d = copy.copy(self.__dict__) for member in strip: del d[member] if (('token_expiry' in d) and isinstance(d['token_expiry'], datetime.datetime)): d['token_expiry'] = d['token_expiry'].strftime(EXPIRY_FORMAT) d['_class'] = t.__name__ d['_module'] = t.__module__ r...
'Creating a JSON representation of an instance of Credentials. Returns: string, a JSON representation of this instance, suitable to pass to from_json().'
def to_json(self):
return self._to_json(Credentials.NON_SERIALIZED_MEMBERS)
'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().'
@classmethod def new_from_json(cls, s):
data = simplejson.loads(s) module = data['_module'] m = __import__(module, fromlist=module.split('.')[:(-1)]) kls = getattr(m, data['_class']) from_json = getattr(kls, 'from_json') return from_json(s)
'Acquires any lock necessary to access this Storage. This lock is not reentrant.'
def acquire_lock(self):
pass
'Release the Storage lock. Trying to release a lock that isn\'t held will result in a RuntimeError.'
def release_lock(self):
pass
'Retrieve credential. The Storage lock must be held when this is called. Returns: oauth2client.client.Credentials'
def locked_get(self):
_abstract()
'Write a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store.'
def locked_put(self, credentials):
_abstract()
'Retrieve credential. The Storage lock must *not* be held when this is called. Returns: oauth2client.client.Credentials'
def get(self):
self.acquire_lock() try: return self.locked_get() finally: self.release_lock()
'Write a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store.'
def put(self, credentials):
self.acquire_lock() try: self.locked_put(credentials) finally: self.release_lock()
'Create an instance of OAuth2Credentials. This constructor is not usually called by the user, instead OAuth2Credentials objects are instantiated by the OAuth2WebServerFlow. Args: access_token: string, access token. client_id: string, client identifier. client_secret: string, client secret. refresh_token: string, refres...
def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, id_token=None):
self.access_token = access_token self.client_id = client_id self.client_secret = client_secret self.refresh_token = refresh_token self.store = None self.token_expiry = token_expiry self.token_uri = token_uri self.user_agent = user_agent self.id_token = id_token self.invalid = Fal...
'Instantiate a Credentials object from a JSON description of it. The JSON should have been produced by calling .to_json() on the object. Args: data: dict, A deserialized JSON object. Returns: An instance of a Credentials subclass.'
@classmethod def from_json(cls, s):
data = simplejson.loads(s) if (('token_expiry' in data) and (not isinstance(data['token_expiry'], datetime.datetime))): try: data['token_expiry'] = datetime.datetime.strptime(data['token_expiry'], EXPIRY_FORMAT) except: data['token_expiry'] = None retval = OAuth2Crede...
'True if the credential is expired or invalid. If the token_expiry isn\'t set, we assume the token doesn\'t expire.'
@property def access_token_expired(self):
if self.invalid: return True if (not self.token_expiry): return False now = datetime.datetime.utcnow() if (now >= self.token_expiry): logger.info('access_token is expired. Now: %s, token_expiry: %s', now, self.token_expiry) return True return False
'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.'
def set_store(self, store):
self.store = store
'Update this Credential from another instance.'
def _updateFromCredential(self, other):
self.__dict__.update(other.__getstate__())
'Trim the state down to something that can be pickled.'
def __getstate__(self):
d = copy.copy(self.__dict__) del d['store'] return d
'Reconstitute the state of the object from being pickled.'
def __setstate__(self, state):
self.__dict__.update(state) self.store = None
'Generate the body that will be used in the refresh request.'
def _generate_refresh_request_body(self):
body = urllib.urlencode({'grant_type': 'refresh_token', 'client_id': self.client_id, 'client_secret': self.client_secret, 'refresh_token': self.refresh_token}) return body
'Generate the headers that will be used in the refresh request.'
def _generate_refresh_request_headers(self):
headers = {'content-type': 'application/x-www-form-urlencoded'} if (self.user_agent is not None): headers['user-agent'] = self.user_agent return headers
'Refreshes the access_token. This method first checks by reading the Storage object if available. If a refresh is still needed, it holds the Storage lock until the refresh is completed.'
def _refresh(self, http_request):
if (not self.store): self._do_refresh_request(http_request) else: self.store.acquire_lock() try: new_cred = self.store.locked_get() if (new_cred and (not new_cred.invalid) and (new_cred.access_token != self.access_token)): logger.info('Updated a...
'Refresh the access_token using the refresh_token. Args: http: An instance of httplib2.Http.request or something that acts like it. Raises: AccessTokenRefreshError: When the refresh fails.'
def _do_refresh_request(self, http_request):
body = self._generate_refresh_request_body() headers = self._generate_refresh_request_headers() logger.info('Refresing access_token') (resp, content) = http_request(self.token_uri, method='POST', body=body, headers=headers) if (resp.status == 200): d = simplejson.loads(content) se...
'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 becaus...
def authorize(self, http):
request_orig = http.request def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): if (not self.access_token): logger.info('Attempting refresh to obtain initial access_token') self._refresh(re...
'Create an instance of OAuth2Credentials This is one of the few types if Credentials that you should contrust, Credentials objects are usually instantiated by a Flow. Args: access_token: string, access token. user_agent: string, The HTTP User-Agent to provide for this application. Notes: store: callable, a callable tha...
def __init__(self, access_token, user_agent):
super(AccessTokenCredentials, self).__init__(access_token, None, None, None, None, None, user_agent)
'Constructor for AssertionFlowCredentials. Args: assertion_type: string, assertion type that will be declared to the auth server user_agent: string, The HTTP User-Agent to provide for this application. token_uri: string, URI for token endpoint. For convenience defaults to Google\'s endpoints but any OAuth 2.0 provider ...
def __init__(self, assertion_type, user_agent, token_uri='https://accounts.google.com/o/oauth2/token', **unused_kwargs):
super(AssertionCredentials, self).__init__(None, None, None, None, None, token_uri, user_agent) self.assertion_type = assertion_type
'Generate the assertion string that will be used in the access token request.'
def _generate_assertion(self):
_abstract()
'Constructor for OAuth2WebServerFlow. Args: client_id: string, client identifier. client_secret: string client secret. scope: string or list of strings, scope(s) of the credentials being requested. user_agent: string, HTTP User-Agent to provide for this application. auth_uri: string, URI for authorization endpoint. For...
def __init__(self, client_id, client_secret, scope, user_agent=None, auth_uri='https://accounts.google.com/o/oauth2/auth', token_uri='https://accounts.google.com/o/oauth2/token', **kwargs):
self.client_id = client_id self.client_secret = client_secret if (type(scope) is list): scope = ' '.join(scope) self.scope = scope self.user_agent = user_agent self.auth_uri = auth_uri self.token_uri = token_uri self.params = {'access_type': 'offline'} self.params.update(k...
'Returns a URI to redirect to the provider. Args: redirect_uri: string, Either the string \'oob\' for a non-web-based application, or a URI that handles the callback from the authorization server. If redirect_uri is \'oob\' then pass in the generated verification code to step2_exchange, otherwise pass in the query para...
def step1_get_authorize_url(self, redirect_uri='oob'):
self.redirect_uri = redirect_uri query = {'response_type': 'code', 'client_id': self.client_id, 'redirect_uri': redirect_uri, 'scope': self.scope} query.update(self.params) parts = list(urlparse.urlparse(self.auth_uri)) query.update(dict(parse_qsl(parts[4]))) parts[4] = urllib.urlencode(query) ...
'Exhanges a code for OAuth2Credentials. Args: code: string or dict, either the code as a string, or a dictionary of the query parameters to the redirect_uri, which contains the code. http: httplib2.Http, optional http instance to use to do the fetch'
def step2_exchange(self, code, http=None):
if (not (isinstance(code, str) or isinstance(code, unicode))): code = code['code'] body = urllib.urlencode({'grant_type': 'authorization_code', 'client_id': self.client_id, 'client_secret': self.client_secret, 'code': code, 'redirect_uri': self.redirect_uri, 'scope': self.scope}) headers = {'content...
'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, ...
def __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):
self.scope = scope self.audience = audience self.app_name = app_identity.get_service_account_name() super(AppAssertionCredentials, self).__init__(assertion_type, None, token_uri)
'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'
def __init__(self, model, key_name, property_name, cache=None):
self._model = model self._key_name = key_name self._property_name = property_name self._cache = cache
'Retrieve Credential from datastore. Returns: oauth2client.Credentials'
def locked_get(self):
if self._cache: json = self._cache.get(self._key_name) if json: return Credentials.new_from_json(json) credential = None entity = self._model.get_by_key_name(self._key_name) if (entity is not None): credential = getattr(entity, self._property_name) if (credent...
'Write a Credentials to the datastore. Args: credentials: Credentials, the credentials to store.'
def locked_put(self, credentials):
entity = self._model.get_or_insert(self._key_name) setattr(entity, self._property_name, credentials) entity.put() if self._cache: self._cache.set(self._key_name, credentials.to_json())
'Constructor for OAuth2Decorator Args: client_id: string, client identifier. client_secret: string client secret. scope: string or list of strings, scope(s) 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 ca...
def __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', message=None, **kwargs):
self.flow = OAuth2WebServerFlow(client_id, client_secret, scope, None, auth_uri, token_uri, **kwargs) self.credentials = None self._request_handler = None self._message = message self._in_error = False
'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.'
def oauth_required(self, method):
def check_oauth(request_handler, *args): if self._in_error: self._display_error_message(request_handler) return user = users.get_current_user() if (not user): request_handler.redirect(users.create_login_url(request_handler.request.uri)) return ...
'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_cre...
def oauth_aware(self, method):
def setup_oauth(request_handler, *args): if self._in_error: self._display_error_message(request_handler) return user = users.get_current_user() if (not user): request_handler.redirect(users.create_login_url(request_handler.request.uri)) return ...
'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.'
def has_credentials(self):
return ((self.credentials is not None) and (not self.credentials.invalid))
'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.'
def authorize_url(self):
callback = self._request_handler.request.relative_url('/oauth2callback') url = self.flow.step1_get_authorize_url(callback) user = users.get_current_user() memcache.set(user.user_id(), pickle.dumps(self.flow), namespace=OAUTH2CLIENT_NAMESPACE) return url
'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.'
def http(self):
return self.credentials.authorize(httplib2.Http())
'Constructor Args: filename: string, File name of client secrets. scope: string, Space separated list of scopes. message: string, A friendly string to display to the user if the clientsecrets file is missing or invalid. The message may contain HTML and will be presented on the web interface for any method that uses the...
def __init__(self, filename, scope, message=None):
try: (client_type, client_info) = clientsecrets.loadfile(filename) if (client_type not in [clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED]): raise InvalidClientSecretsError("OAuth2Decorator doesn't support this OAuth 2.0 flow.") super(OAuth2DecoratorFromCl...
'Acquires any lock necessary to access this Storage. This lock is not reentrant.'
def acquire_lock(self):
self._lock.acquire()
'Release the Storage lock. Trying to release a lock that isn\'t held will result in a RuntimeError.'
def release_lock(self):
self._lock.release()
'Retrieve Credential from file. Returns: oauth2client.client.Credentials'
def locked_get(self):
credentials = None try: f = open(self._filename, 'rb') content = f.read() f.close() except IOError: return credentials try: credentials = Credentials.new_from_json(content) credentials.set_store(self) except ValueError: pass return credenti...
'Create an empty file if necessary. This method will not initialize the file. Instead it implements a simple version of "touch" to ensure the file has been created.'
def _create_file_if_needed(self):
if (not os.path.exists(self._filename)): old_umask = os.umask(127) try: open(self._filename, 'a+b').close() finally: os.umask(old_umask)
'Write Credentials to file. Args: credentials: Credentials, the credentials to store.'
def locked_put(self, credentials):
self._create_file_if_needed() f = open(self._filename, 'wb') f.write(credentials.to_json()) f.close()
'Initialize the class. This will create the file if necessary.'
def __init__(self, filename, warn_on_readonly=True):
self._filename = filename self._thread_lock = threading.Lock() self._file_handle = None self._read_only = False self._warn_on_readonly = warn_on_readonly self._create_file_if_needed() self._data = None
'Acquires any lock necessary to access this Storage. This lock is not reentrant.'
def acquire_lock(self):
self._multistore._lock()
'Release the Storage lock. Trying to release a lock that isn\'t held will result in a RuntimeError.'
def release_lock(self):
self._multistore._unlock()
'Retrieve credential. The Storage lock must be held when this is called. Returns: oauth2client.client.Credentials'
def locked_get(self):
credential = self._multistore._get_credential(self._client_id, self._user_agent, self._scope) if credential: credential.set_store(self) return credential
'Write a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store.'
def locked_put(self, credentials):
self._multistore._update_credential(credentials, self._scope)
'Create an empty file if necessary. This method will not initialize the file. Instead it implements a simple version of "touch" to ensure the file has been created.'
def _create_file_if_needed(self):
if (not os.path.exists(self._filename)): old_umask = os.umask(127) try: open(self._filename, 'a+b').close() finally: os.umask(old_umask)
'Lock the entire multistore.'
def _lock(self):
self._thread_lock.acquire() try: self._file_handle = open(self._filename, 'r+b') fcntl.lockf(self._file_handle.fileno(), fcntl.LOCK_EX) except IOError as e: if (e.errno != errno.EACCES): raise e self._file_handle = open(self._filename, 'rb') self._read_onl...
'Release the lock on the multistore.'
def _unlock(self):
if (not self._read_only): fcntl.lockf(self._file_handle.fileno(), fcntl.LOCK_UN) self._file_handle.close() self._thread_lock.release()
'Get the raw content of the multistore file. The multistore must be locked when this is called. Returns: The contents of the multistore decoded as JSON.'
def _locked_json_read(self):
assert self._thread_lock.locked() self._file_handle.seek(0) return simplejson.load(self._file_handle)
'Write a JSON serializable data structure to the multistore. The multistore must be locked when this is called. Args: data: The data to be serialized and written.'
def _locked_json_write(self, data):
assert self._thread_lock.locked() if self._read_only: return self._file_handle.seek(0) simplejson.dump(data, self._file_handle, sort_keys=True, indent=2) self._file_handle.truncate()
'Refresh the contents of the multistore. The multistore must be locked when this is called. Raises: NewerCredentialStoreError: Raised when a newer client has written the store.'
def _refresh_data_cache(self):
self._data = {} try: raw_data = self._locked_json_read() except Exception: logger.warn('Credential data store could not be loaded. Will ignore and overwrite.') return version = 0 try: version = raw_data['file_version'] except Exceptio...
'Load a credential from our JSON serialization. Args: cred_entry: A dict entry from the data member of our format Returns: (key, cred) where the key is the key tuple and the cred is the OAuth2Credential object.'
def _decode_credential_from_json(self, cred_entry):
raw_key = cred_entry['key'] client_id = raw_key['clientId'] user_agent = raw_key['userAgent'] scope = raw_key['scope'] key = (client_id, user_agent, scope) credential = None credential = Credentials.new_from_json(simplejson.dumps(cred_entry['credential'])) return (key, credential)
'Write the cached data back out. The multistore must be locked.'
def _write(self):
raw_data = {'file_version': 1} raw_creds = [] raw_data['data'] = raw_creds for (cred_key, cred) in self._data.items(): raw_key = {'clientId': cred_key[0], 'userAgent': cred_key[1], 'scope': cred_key[2]} raw_cred = simplejson.loads(cred.to_json()) raw_creds.append({'key': raw_key,...
'Get a credential from the multistore. The multistore must be locked. Args: client_id: The client_id for the credential user_agent: The user agent for the credential scope: A string for the scope(s) being requested Returns: The credential specified or None if not present'
def _get_credential(self, client_id, user_agent, scope):
key = (client_id, user_agent, scope) return self._data.get(key, None)