google-api-python-client-1.2/0000750017135500116100000000000012200467672017125 5ustar jcgregorioeng00000000000000google-api-python-client-1.2/setpath.sh0000640017135500116100000000004612173557443021137 0ustar jcgregorioeng00000000000000export PYTHONPATH=`pwd`:${PYTHONPATH} google-api-python-client-1.2/oauth2client/0000750017135500116100000000000012200467672021526 5ustar jcgregorioeng00000000000000google-api-python-client-1.2/oauth2client/locked_file.py0000640017135500116100000002616312173557443024356 0ustar jcgregorioeng00000000000000# Copyright 2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Locked file interface that should work on Unix and Windows pythons. This module first tries to use fcntl locking to ensure serialized access to a file, then falls back on a lock file if that is unavialable. Usage: f = LockedFile('filename', 'r+b', 'rb') f.open_and_lock() if f.is_locked(): print 'Acquired filename with r+b mode' f.file_handle().write('locked data') else: print 'Aquired filename with rb mode' f.unlock_and_close() """ __author__ = 'cache@google.com (David T McWherter)' import errno import logging import os import time from oauth2client import util logger = logging.getLogger(__name__) class CredentialsFileSymbolicLinkError(Exception): """Credentials files must not be symbolic links.""" class AlreadyLockedException(Exception): """Trying to lock a file that has already been locked by the LockedFile.""" pass def validate_file(filename): if os.path.islink(filename): raise CredentialsFileSymbolicLinkError( 'File: %s is a symbolic link.' % filename) class _Opener(object): """Base class for different locking primitives.""" def __init__(self, filename, mode, fallback_mode): """Create an Opener. Args: filename: string, The pathname of the file. mode: string, The preferred mode to access the file with. fallback_mode: string, The mode to use if locking fails. """ self._locked = False self._filename = filename self._mode = mode self._fallback_mode = fallback_mode self._fh = None def is_locked(self): """Was the file locked.""" return self._locked def file_handle(self): """The file handle to the file. Valid only after opened.""" return self._fh def filename(self): """The filename that is being locked.""" return self._filename def open_and_lock(self, timeout, delay): """Open the file and lock it. Args: timeout: float, How long to try to lock for. delay: float, How long to wait between retries. """ pass def unlock_and_close(self): """Unlock and close the file.""" pass class _PosixOpener(_Opener): """Lock files using Posix advisory lock files.""" def open_and_lock(self, timeout, delay): """Open the file and lock it. Tries to create a .lock file next to the file we're trying to open. Args: timeout: float, How long to try to lock for. delay: float, How long to wait between retries. Raises: AlreadyLockedException: if the lock is already acquired. IOError: if the open fails. CredentialsFileSymbolicLinkError if the file is a symbolic link. """ if self._locked: raise AlreadyLockedException('File %s is already locked' % self._filename) self._locked = False validate_file(self._filename) try: self._fh = open(self._filename, self._mode) except IOError, e: # If we can't access with _mode, try _fallback_mode and don't lock. if e.errno == errno.EACCES: self._fh = open(self._filename, self._fallback_mode) return lock_filename = self._posix_lockfile(self._filename) start_time = time.time() while True: try: self._lock_fd = os.open(lock_filename, os.O_CREAT|os.O_EXCL|os.O_RDWR) self._locked = True break except OSError, e: if e.errno != errno.EEXIST: raise if (time.time() - start_time) >= timeout: logger.warn('Could not acquire lock %s in %s seconds' % ( lock_filename, timeout)) # Close the file and open in fallback_mode. if self._fh: self._fh.close() self._fh = open(self._filename, self._fallback_mode) return time.sleep(delay) def unlock_and_close(self): """Unlock a file by removing the .lock file, and close the handle.""" if self._locked: lock_filename = self._posix_lockfile(self._filename) os.close(self._lock_fd) os.unlink(lock_filename) self._locked = False self._lock_fd = None if self._fh: self._fh.close() def _posix_lockfile(self, filename): """The name of the lock file to use for posix locking.""" return '%s.lock' % filename try: import fcntl class _FcntlOpener(_Opener): """Open, lock, and unlock a file using fcntl.lockf.""" def open_and_lock(self, timeout, delay): """Open the file and lock it. Args: timeout: float, How long to try to lock for. delay: float, How long to wait between retries Raises: AlreadyLockedException: if the lock is already acquired. IOError: if the open fails. CredentialsFileSymbolicLinkError if the file is a symbolic link. """ if self._locked: raise AlreadyLockedException('File %s is already locked' % self._filename) start_time = time.time() validate_file(self._filename) try: self._fh = open(self._filename, self._mode) except IOError, e: # If we can't access with _mode, try _fallback_mode and don't lock. if e.errno == errno.EACCES: self._fh = open(self._filename, self._fallback_mode) return # We opened in _mode, try to lock the file. while True: try: fcntl.lockf(self._fh.fileno(), fcntl.LOCK_EX) self._locked = True return except IOError, e: # If not retrying, then just pass on the error. if timeout == 0: raise e if e.errno != errno.EACCES: raise e # We could not acquire the lock. Try again. if (time.time() - start_time) >= timeout: logger.warn('Could not lock %s in %s seconds' % ( self._filename, timeout)) if self._fh: self._fh.close() self._fh = open(self._filename, self._fallback_mode) return time.sleep(delay) def unlock_and_close(self): """Close and unlock the file using the fcntl.lockf primitive.""" if self._locked: fcntl.lockf(self._fh.fileno(), fcntl.LOCK_UN) self._locked = False if self._fh: self._fh.close() except ImportError: _FcntlOpener = None try: import pywintypes import win32con import win32file class _Win32Opener(_Opener): """Open, lock, and unlock a file using windows primitives.""" # Error #33: # 'The process cannot access the file because another process' FILE_IN_USE_ERROR = 33 # Error #158: # 'The segment is already unlocked.' FILE_ALREADY_UNLOCKED_ERROR = 158 def open_and_lock(self, timeout, delay): """Open the file and lock it. Args: timeout: float, How long to try to lock for. delay: float, How long to wait between retries Raises: AlreadyLockedException: if the lock is already acquired. IOError: if the open fails. CredentialsFileSymbolicLinkError if the file is a symbolic link. """ if self._locked: raise AlreadyLockedException('File %s is already locked' % self._filename) start_time = time.time() validate_file(self._filename) try: self._fh = open(self._filename, self._mode) except IOError, e: # If we can't access with _mode, try _fallback_mode and don't lock. if e.errno == errno.EACCES: self._fh = open(self._filename, self._fallback_mode) return # We opened in _mode, try to lock the file. while True: try: hfile = win32file._get_osfhandle(self._fh.fileno()) win32file.LockFileEx( hfile, (win32con.LOCKFILE_FAIL_IMMEDIATELY| win32con.LOCKFILE_EXCLUSIVE_LOCK), 0, -0x10000, pywintypes.OVERLAPPED()) self._locked = True return except pywintypes.error, e: if timeout == 0: raise e # If the error is not that the file is already in use, raise. if e[0] != _Win32Opener.FILE_IN_USE_ERROR: raise # We could not acquire the lock. Try again. if (time.time() - start_time) >= timeout: logger.warn('Could not lock %s in %s seconds' % ( self._filename, timeout)) if self._fh: self._fh.close() self._fh = open(self._filename, self._fallback_mode) return time.sleep(delay) def unlock_and_close(self): """Close and unlock the file using the win32 primitive.""" if self._locked: try: hfile = win32file._get_osfhandle(self._fh.fileno()) win32file.UnlockFileEx(hfile, 0, -0x10000, pywintypes.OVERLAPPED()) except pywintypes.error, e: if e[0] != _Win32Opener.FILE_ALREADY_UNLOCKED_ERROR: raise self._locked = False if self._fh: self._fh.close() except ImportError: _Win32Opener = None class LockedFile(object): """Represent a file that has exclusive access.""" @util.positional(4) def __init__(self, filename, mode, fallback_mode, use_native_locking=True): """Construct a LockedFile. Args: filename: string, The path of the file to open. mode: string, The mode to try to open the file with. fallback_mode: string, The mode to use if locking fails. use_native_locking: bool, Whether or not fcntl/win32 locking is used. """ opener = None if not opener and use_native_locking: if _Win32Opener: opener = _Win32Opener(filename, mode, fallback_mode) if _FcntlOpener: opener = _FcntlOpener(filename, mode, fallback_mode) if not opener: opener = _PosixOpener(filename, mode, fallback_mode) self._opener = opener def filename(self): """Return the filename we were constructed with.""" return self._opener._filename def file_handle(self): """Return the file_handle to the opened file.""" return self._opener.file_handle() def is_locked(self): """Return whether we successfully locked the file.""" return self._opener.is_locked() def open_and_lock(self, timeout=0, delay=0.05): """Open the file, trying to lock it. Args: timeout: float, The number of seconds to try to acquire the lock. delay: float, The number of seconds to wait between retry attempts. Raises: AlreadyLockedException: if the lock is already acquired. IOError: if the open fails. """ self._opener.open_and_lock(timeout, delay) def unlock_and_close(self): """Unlock and close a file.""" self._opener.unlock_and_close() google-api-python-client-1.2/oauth2client/tools.py0000640017135500116100000002023012200460221023215 0ustar jcgregorioeng00000000000000# Copyright (C) 2013 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Command-line tools for authenticating via OAuth 2.0 Do the OAuth 2.0 Web Server dance for a command line application. Stores the generated credentials in a common file that is used by other example apps in the same directory. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' __all__ = ['argparser', 'run_flow', 'run', 'message_if_missing'] import BaseHTTPServer import argparse import httplib2 import logging import os import socket import sys import webbrowser from oauth2client import client from oauth2client import file from oauth2client import util try: from urlparse import parse_qsl except ImportError: from cgi import parse_qsl _CLIENT_SECRETS_MESSAGE = """WARNING: Please configure OAuth 2.0 To make this sample run you will need to populate the client_secrets.json file found at: %s with information from the APIs Console . """ # run_parser is an ArgumentParser that contains command-line options expected # by tools.run(). Pass it in as part of the 'parents' argument to your own # ArgumentParser. argparser = argparse.ArgumentParser(add_help=False) argparser.add_argument('--auth_host_name', default='localhost', help='Hostname when running a local web server.') argparser.add_argument('--noauth_local_webserver', action='store_true', default=False, help='Do not run a local web server.') argparser.add_argument('--auth_host_port', default=[8080, 8090], type=int, nargs='*', help='Port web server should listen on.') argparser.add_argument('--logging_level', default='ERROR', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], help='Set the logging level of detail.') class ClientRedirectServer(BaseHTTPServer.HTTPServer): """A server to handle OAuth 2.0 redirects back to localhost. Waits for a single request and parses the query parameters into query_params and then stops serving. """ query_params = {} class ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler): """A handler for OAuth 2.0 redirects back to localhost. Waits for a single request and parses the query parameters into the servers query_params and then stops serving. """ def do_GET(s): """Handle a GET request. Parses the query parameters and prints a message if the flow has completed. Note that we can't detect if an error occurred. """ s.send_response(200) s.send_header("Content-type", "text/html") s.end_headers() query = s.path.split('?', 1)[-1] query = dict(parse_qsl(query)) s.server.query_params = query s.wfile.write("Authentication Status") s.wfile.write("

The authentication flow has completed.

") s.wfile.write("") def log_message(self, format, *args): """Do not log messages to stdout while running as command line program.""" pass @util.positional(3) def run_flow(flow, storage, flags, http=None): """Core code for a command-line application. The run() function is called from your application and runs through all the steps to obtain credentials. It takes a Flow argument and attempts to open an authorization server page in the user's default web browser. The server asks the user to grant your application access to the user's data. If the user grants access, the run() function returns new credentials. The new credentials are also stored in the Storage argument, which updates the file associated with the Storage object. It presumes it is run from a command-line application and supports the following flags: --auth_host_name: Host name to use when running a local web server to handle redirects during OAuth authorization. (default: 'localhost') --auth_host_port: Port to use when running a local web server to handle redirects during OAuth authorization.; repeat this option to specify a list of values (default: '[8080, 8090]') (an integer) --[no]auth_local_webserver: Run a local web server to handle redirects during OAuth authorization. (default: 'true') The tools module defines an ArgumentParser the already contains the flag definitions that run() requires. You can pass that ArgumentParser to your ArgumentParser constructor: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, parents=[tools.run_parser]) flags = parser.parse_args(argv) Args: flow: Flow, an OAuth 2.0 Flow to step through. storage: Storage, a Storage to store the credential in. flags: argparse.ArgumentParser, the command-line flags. http: An instance of httplib2.Http.request or something that acts like it. Returns: Credentials, the obtained credential. """ logging.getLogger().setLevel(getattr(logging, flags.logging_level)) if not flags.noauth_local_webserver: success = False port_number = 0 for port in flags.auth_host_port: port_number = port try: httpd = ClientRedirectServer((flags.auth_host_name, port), ClientRedirectHandler) except socket.error, e: pass else: success = True break flags.noauth_local_webserver = not success if not success: print 'Failed to start a local webserver listening on either port 8080' print 'or port 9090. Please check your firewall settings and locally' print 'running programs that may be blocking or using those ports.' print print 'Falling back to --noauth_local_webserver and continuing with', print 'authorization.' print if not flags.noauth_local_webserver: oauth_callback = 'http://%s:%s/' % (flags.auth_host_name, port_number) else: oauth_callback = client.OOB_CALLBACK_URN flow.redirect_uri = oauth_callback authorize_url = flow.step1_get_authorize_url() if not flags.noauth_local_webserver: webbrowser.open(authorize_url, new=1, autoraise=True) print 'Your browser has been opened to visit:' print print ' ' + authorize_url print print 'If your browser is on a different machine then exit and re-run this' print 'application with the command-line parameter ' print print ' --noauth_local_webserver' print else: print 'Go to the following link in your browser:' print print ' ' + authorize_url print code = None if not flags.noauth_local_webserver: httpd.handle_request() if 'error' in httpd.query_params: sys.exit('Authentication request was rejected.') if 'code' in httpd.query_params: code = httpd.query_params['code'] else: print 'Failed to find "code" in the query parameters of the redirect.' sys.exit('Try running with --noauth_local_webserver.') else: code = raw_input('Enter verification code: ').strip() try: credential = flow.step2_exchange(code, http=http) except client.FlowExchangeError, e: sys.exit('Authentication has failed: %s' % e) storage.put(credential) credential.set_store(storage) print 'Authentication successful.' return credential def message_if_missing(filename): """Helpful message to display if the CLIENT_SECRETS file is missing.""" return _CLIENT_SECRETS_MESSAGE % filename try: from old_run import run from old_run import FLAGS except ImportError: def run(*args, **kwargs): raise NotImplementedError( 'The gflags library must be installed to use tools.run(). ' 'Please install gflags or preferrably switch to using ' 'tools.run_flow().') google-api-python-client-1.2/oauth2client/keyring_storage.py0000640017135500116100000000623312173557443025306 0ustar jcgregorioeng00000000000000# Copyright (C) 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A keyring based Storage. A Storage for Credentials that uses the keyring module. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import keyring import threading from client import Storage as BaseStorage from client import Credentials class Storage(BaseStorage): """Store and retrieve a single credential to and from the keyring. To use this module you must have the keyring module installed. See . This is an optional module and is not installed with oauth2client by default because it does not work on all the platforms that oauth2client supports, such as Google App Engine. The keyring module is a cross-platform library for access the keyring capabilities of the local system. The user will be prompted for their keyring password when this module is used, and the manner in which the user is prompted will vary per platform. Usage: from oauth2client.keyring_storage import Storage s = Storage('name_of_application', 'user1') credentials = s.get() """ def __init__(self, service_name, user_name): """Constructor. Args: service_name: string, The name of the service under which the credentials are stored. user_name: string, The name of the user to store credentials for. """ self._service_name = service_name self._user_name = user_name self._lock = threading.Lock() def acquire_lock(self): """Acquires any lock necessary to access this Storage. This lock is not reentrant.""" self._lock.acquire() def release_lock(self): """Release the Storage lock. Trying to release a lock that isn't held will result in a RuntimeError. """ self._lock.release() def locked_get(self): """Retrieve Credential from file. Returns: oauth2client.client.Credentials """ credentials = None content = keyring.get_password(self._service_name, self._user_name) if content is not None: try: credentials = Credentials.new_from_json(content) credentials.set_store(self) except ValueError: pass return credentials def locked_put(self, credentials): """Write Credentials to file. Args: credentials: Credentials, the credentials to store. """ keyring.set_password(self._service_name, self._user_name, credentials.to_json()) def locked_delete(self): """Delete Credentials file. Args: credentials: Credentials, the credentials to store. """ keyring.set_password(self._service_name, self._user_name, '') google-api-python-client-1.2/oauth2client/file.py0000640017135500116100000000613012173557443023025 0ustar jcgregorioeng00000000000000# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for OAuth. Utilities for making it easier to work with OAuth 2.0 credentials. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import os import stat import threading from anyjson import simplejson from client import Storage as BaseStorage from client import Credentials class CredentialsFileSymbolicLinkError(Exception): """Credentials files must not be symbolic links.""" class Storage(BaseStorage): """Store and retrieve a single credential to and from a file.""" def __init__(self, filename): self._filename = filename self._lock = threading.Lock() def _validate_file(self): if os.path.islink(self._filename): raise CredentialsFileSymbolicLinkError( 'File: %s is a symbolic link.' % self._filename) def acquire_lock(self): """Acquires any lock necessary to access this Storage. This lock is not reentrant.""" self._lock.acquire() def release_lock(self): """Release the Storage lock. Trying to release a lock that isn't held will result in a RuntimeError. """ self._lock.release() def locked_get(self): """Retrieve Credential from file. Returns: oauth2client.client.Credentials Raises: CredentialsFileSymbolicLinkError if the file is a symbolic link. """ credentials = None self._validate_file() 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 credentials def _create_file_if_needed(self): """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. """ if not os.path.exists(self._filename): old_umask = os.umask(0177) try: open(self._filename, 'a+b').close() finally: os.umask(old_umask) def locked_put(self, credentials): """Write Credentials to file. Args: credentials: Credentials, the credentials to store. Raises: CredentialsFileSymbolicLinkError if the file is a symbolic link. """ self._create_file_if_needed() self._validate_file() f = open(self._filename, 'wb') f.write(credentials.to_json()) f.close() def locked_delete(self): """Delete Credentials file. Args: credentials: Credentials, the credentials to store. """ os.unlink(self._filename) google-api-python-client-1.2/oauth2client/gce.py0000640017135500116100000000573612173557443022657 0ustar jcgregorioeng00000000000000# Copyright (C) 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for Google Compute Engine Utilities for making it easier to use OAuth 2.0 on Google Compute Engine. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import httplib2 import logging import uritemplate from oauth2client import util from oauth2client.anyjson import simplejson from oauth2client.client import AccessTokenRefreshError from oauth2client.client import AssertionCredentials logger = logging.getLogger(__name__) # URI Template for the endpoint that returns access_tokens. META = ('http://metadata.google.internal/0.1/meta-data/service-accounts/' 'default/acquire{?scope}') class AppAssertionCredentials(AssertionCredentials): """Credentials object for Compute Engine Assertion Grants This object will allow a Compute Engine instance 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 Compute Engine instance itself. 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. """ @util.positional(2) def __init__(self, scope, **kwargs): """Constructor for AppAssertionCredentials Args: scope: string or iterable of strings, scope(s) of the credentials being requested. """ self.scope = util.scopes_to_string(scope) # Assertion type is no longer used, but still in the parent class signature. super(AppAssertionCredentials, self).__init__(None) @classmethod def from_json(cls, json): data = simplejson.loads(json) return AppAssertionCredentials(data['scope']) def _refresh(self, http_request): """Refreshes the access_token. Skip all the storage hoops and just refresh using the API. Args: http_request: callable, a callable that matches the method signature of httplib2.Http.request, used to make the refresh request. Raises: AccessTokenRefreshError: When the refresh fails. """ uri = uritemplate.expand(META, {'scope': self.scope}) response, content = http_request(uri) if response.status == 200: try: d = simplejson.loads(content) except StandardError, e: raise AccessTokenRefreshError(str(e)) self.access_token = d['accessToken'] else: raise AccessTokenRefreshError(content) google-api-python-client-1.2/oauth2client/util.py0000640017135500116100000001304612173557443023067 0ustar jcgregorioeng00000000000000#!/usr/bin/env python # # Copyright 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """Common utility library.""" __author__ = ['rafek@google.com (Rafe Kaplan)', 'guido@google.com (Guido van Rossum)', ] __all__ = [ 'positional', 'POSITIONAL_WARNING', 'POSITIONAL_EXCEPTION', 'POSITIONAL_IGNORE', ] import inspect import logging import types import urllib import urlparse try: from urlparse import parse_qsl except ImportError: from cgi import parse_qsl logger = logging.getLogger(__name__) POSITIONAL_WARNING = 'WARNING' POSITIONAL_EXCEPTION = 'EXCEPTION' POSITIONAL_IGNORE = 'IGNORE' POSITIONAL_SET = frozenset([POSITIONAL_WARNING, POSITIONAL_EXCEPTION, POSITIONAL_IGNORE]) positional_parameters_enforcement = POSITIONAL_WARNING def positional(max_positional_args): """A decorator to declare that only the first N arguments my be positional. This decorator makes it easy to support Python 3 style key-word only parameters. For example, in Python 3 it is possible to write: def fn(pos1, *, kwonly1=None, kwonly1=None): ... All named parameters after * must be a keyword: fn(10, 'kw1', 'kw2') # Raises exception. fn(10, kwonly1='kw1') # Ok. Example: To define a function like above, do: @positional(1) def fn(pos1, kwonly1=None, kwonly2=None): ... If no default value is provided to a keyword argument, it becomes a required keyword argument: @positional(0) def fn(required_kw): ... This must be called with the keyword parameter: fn() # Raises exception. fn(10) # Raises exception. fn(required_kw=10) # Ok. When defining instance or class methods always remember to account for 'self' and 'cls': class MyClass(object): @positional(2) def my_method(self, pos1, kwonly1=None): ... @classmethod @positional(2) def my_method(cls, pos1, kwonly1=None): ... The positional decorator behavior is controlled by util.positional_parameters_enforcement, which may be set to POSITIONAL_EXCEPTION, POSITIONAL_WARNING or POSITIONAL_IGNORE to raise an exception, log a warning, or do nothing, respectively, if a declaration is violated. Args: max_positional_arguments: Maximum number of positional arguments. All parameters after the this index must be keyword only. Returns: A decorator that prevents using arguments after max_positional_args from being used as positional parameters. Raises: TypeError if a key-word only argument is provided as a positional parameter, but only if util.positional_parameters_enforcement is set to POSITIONAL_EXCEPTION. """ def positional_decorator(wrapped): def positional_wrapper(*args, **kwargs): if len(args) > max_positional_args: plural_s = '' if max_positional_args != 1: plural_s = 's' message = '%s() takes at most %d positional argument%s (%d given)' % ( wrapped.__name__, max_positional_args, plural_s, len(args)) if positional_parameters_enforcement == POSITIONAL_EXCEPTION: raise TypeError(message) elif positional_parameters_enforcement == POSITIONAL_WARNING: logger.warning(message) else: # IGNORE pass return wrapped(*args, **kwargs) return positional_wrapper if isinstance(max_positional_args, (int, long)): return positional_decorator else: args, _, _, defaults = inspect.getargspec(max_positional_args) return positional(len(args) - len(defaults))(max_positional_args) def scopes_to_string(scopes): """Converts scope value to a string. If scopes is a string then it is simply passed through. If scopes is an iterable then a string is returned that is all the individual scopes concatenated with spaces. Args: scopes: string or iterable of strings, the scopes. Returns: The scopes formatted as a single string. """ if isinstance(scopes, types.StringTypes): return scopes else: return ' '.join(scopes) def dict_to_tuple_key(dictionary): """Converts a dictionary to a tuple that can be used as an immutable key. The resulting key is always sorted so that logically equivalent dictionaries always produce an identical tuple for a key. Args: dictionary: the dictionary to use as the key. Returns: A tuple representing the dictionary in it's naturally sorted ordering. """ return tuple(sorted(dictionary.items())) def _add_query_parameter(url, name, value): """Adds a query parameter to a url. Replaces the current value if it already exists in the URL. Args: url: string, url to add the query parameter to. name: string, query parameter name. value: string, query parameter value. Returns: Updated query parameter. Does not update the url if value is None. """ if value is None: return url else: parsed = list(urlparse.urlparse(url)) q = dict(parse_qsl(parsed[4])) q[name] = value parsed[4] = urllib.urlencode(q) return urlparse.urlunparse(parsed) google-api-python-client-1.2/oauth2client/clientsecrets.py0000640017135500116100000001046512173557443024763 0ustar jcgregorioeng00000000000000# Copyright (C) 2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for reading OAuth 2.0 client secret files. A client_secrets.json file contains all the information needed to interact with an OAuth 2.0 protected service. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' from anyjson import simplejson # Properties that make a client_secrets.json file valid. TYPE_WEB = 'web' TYPE_INSTALLED = 'installed' VALID_CLIENT = { TYPE_WEB: { 'required': [ 'client_id', 'client_secret', 'redirect_uris', 'auth_uri', 'token_uri', ], 'string': [ 'client_id', 'client_secret', ], }, TYPE_INSTALLED: { 'required': [ 'client_id', 'client_secret', 'redirect_uris', 'auth_uri', 'token_uri', ], 'string': [ 'client_id', 'client_secret', ], }, } class Error(Exception): """Base error for this module.""" pass class InvalidClientSecretsError(Error): """Format of ClientSecrets file is invalid.""" pass def _validate_clientsecrets(obj): if obj is None or len(obj) != 1: raise InvalidClientSecretsError('Invalid file format.') client_type = obj.keys()[0] if client_type not in VALID_CLIENT.keys(): raise InvalidClientSecretsError('Unknown client type: %s.' % client_type) client_info = obj[client_type] for prop_name in VALID_CLIENT[client_type]['required']: if prop_name not in client_info: raise InvalidClientSecretsError( 'Missing property "%s" in a client type of "%s".' % (prop_name, client_type)) for prop_name in VALID_CLIENT[client_type]['string']: if client_info[prop_name].startswith('[['): raise InvalidClientSecretsError( 'Property "%s" is not configured.' % prop_name) return client_type, client_info def load(fp): obj = simplejson.load(fp) return _validate_clientsecrets(obj) def loads(s): obj = simplejson.loads(s) return _validate_clientsecrets(obj) def _loadfile(filename): try: fp = file(filename, 'r') try: obj = simplejson.load(fp) finally: fp.close() except IOError: raise InvalidClientSecretsError('File not found: "%s"' % filename) return _validate_clientsecrets(obj) def loadfile(filename, cache=None): """Loading of client_secrets JSON file, optionally backed by a cache. Typical cache storage would be App Engine memcache service, but you can pass in any other cache client that implements these methods: - get(key, namespace=ns) - set(key, value, namespace=ns) Usage: # without caching client_type, client_info = loadfile('secrets.json') # using App Engine memcache service from google.appengine.api import memcache client_type, client_info = loadfile('secrets.json', cache=memcache) Args: filename: string, Path to a client_secrets.json file on a filesystem. cache: An optional cache service client that implements get() and set() methods. If not specified, the file is always being loaded from a filesystem. Raises: InvalidClientSecretsError: In case of a validation error or some I/O failure. Can happen only on cache miss. Returns: (client_type, client_info) tuple, as _loadfile() normally would. JSON contents is validated only during first load. Cache hits are not validated. """ _SECRET_NAMESPACE = 'oauth2client:secrets#ns' if not cache: return _loadfile(filename) obj = cache.get(filename, namespace=_SECRET_NAMESPACE) if obj is None: client_type, client_info = _loadfile(filename) obj = {client_type: client_info} cache.set(filename, obj, namespace=_SECRET_NAMESPACE) return obj.iteritems().next() google-api-python-client-1.2/oauth2client/old_run.py0000640017135500116100000001265412173557443023560 0ustar jcgregorioeng00000000000000# Copyright (C) 2013 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module holds the old run() function which is deprecated, the tools.run_flow() function should be used in its place.""" import logging import socket import sys import webbrowser import gflags from oauth2client import client from oauth2client import util from tools import ClientRedirectHandler from tools import ClientRedirectServer FLAGS = gflags.FLAGS gflags.DEFINE_boolean('auth_local_webserver', True, ('Run a local web server to handle redirects during ' 'OAuth authorization.')) gflags.DEFINE_string('auth_host_name', 'localhost', ('Host name to use when running a local web server to ' 'handle redirects during OAuth authorization.')) gflags.DEFINE_multi_int('auth_host_port', [8080, 8090], ('Port to use when running a local web server to ' 'handle redirects during OAuth authorization.')) @util.positional(2) def run(flow, storage, http=None): """Core code for a command-line application. The run() function is called from your application and runs through all the steps to obtain credentials. It takes a Flow argument and attempts to open an authorization server page in the user's default web browser. The server asks the user to grant your application access to the user's data. If the user grants access, the run() function returns new credentials. The new credentials are also stored in the Storage argument, which updates the file associated with the Storage object. It presumes it is run from a command-line application and supports the following flags: --auth_host_name: Host name to use when running a local web server to handle redirects during OAuth authorization. (default: 'localhost') --auth_host_port: Port to use when running a local web server to handle redirects during OAuth authorization.; repeat this option to specify a list of values (default: '[8080, 8090]') (an integer) --[no]auth_local_webserver: Run a local web server to handle redirects during OAuth authorization. (default: 'true') Since it uses flags make sure to initialize the gflags module before calling run(). Args: flow: Flow, an OAuth 2.0 Flow to step through. storage: Storage, a Storage to store the credential in. http: An instance of httplib2.Http.request or something that acts like it. Returns: Credentials, the obtained credential. """ logging.warning('This function, oauth2client.tools.run(), and the use of ' 'the gflags library are deprecated and will be removed in a future ' 'version of the library.') if FLAGS.auth_local_webserver: success = False port_number = 0 for port in FLAGS.auth_host_port: port_number = port try: httpd = ClientRedirectServer((FLAGS.auth_host_name, port), ClientRedirectHandler) except socket.error, e: pass else: success = True break FLAGS.auth_local_webserver = success if not success: print 'Failed to start a local webserver listening on either port 8080' print 'or port 9090. Please check your firewall settings and locally' print 'running programs that may be blocking or using those ports.' print print 'Falling back to --noauth_local_webserver and continuing with', print 'authorization.' print if FLAGS.auth_local_webserver: oauth_callback = 'http://%s:%s/' % (FLAGS.auth_host_name, port_number) else: oauth_callback = client.OOB_CALLBACK_URN flow.redirect_uri = oauth_callback authorize_url = flow.step1_get_authorize_url() if FLAGS.auth_local_webserver: webbrowser.open(authorize_url, new=1, autoraise=True) print 'Your browser has been opened to visit:' print print ' ' + authorize_url print print 'If your browser is on a different machine then exit and re-run' print 'this application with the command-line parameter ' print print ' --noauth_local_webserver' print else: print 'Go to the following link in your browser:' print print ' ' + authorize_url print code = None if FLAGS.auth_local_webserver: httpd.handle_request() if 'error' in httpd.query_params: sys.exit('Authentication request was rejected.') if 'code' in httpd.query_params: code = httpd.query_params['code'] else: print 'Failed to find "code" in the query parameters of the redirect.' sys.exit('Try running with --noauth_local_webserver.') else: code = raw_input('Enter verification code: ').strip() try: credential = flow.step2_exchange(code, http=http) except client.FlowExchangeError, e: sys.exit('Authentication has failed: %s' % e) storage.put(credential) credential.set_store(storage) print 'Authentication successful.' return credential google-api-python-client-1.2/oauth2client/multistore_file.py0000640017135500116100000003315712173557443025325 0ustar jcgregorioeng00000000000000# Copyright 2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Multi-credential file store with lock support. This module implements a JSON credential store where multiple credentials can be stored in one file. That file supports locking both in a single process and across processes. The credential themselves are keyed off of: * client_id * user_agent * scope The format of the stored data is like so: { 'file_version': 1, 'data': [ { 'key': { 'clientId': '', 'userAgent': '', 'scope': '' }, 'credential': { # JSON serialized Credentials. } } ] } """ __author__ = 'jbeda@google.com (Joe Beda)' import base64 import errno import logging import os import threading from anyjson import simplejson from oauth2client.client import Storage as BaseStorage from oauth2client.client import Credentials from oauth2client import util from locked_file import LockedFile logger = logging.getLogger(__name__) # A dict from 'filename'->_MultiStore instances _multistores = {} _multistores_lock = threading.Lock() class Error(Exception): """Base error for this module.""" pass class NewerCredentialStoreError(Error): """The credential store is a newer version that supported.""" pass @util.positional(4) def get_credential_storage(filename, client_id, user_agent, scope, warn_on_readonly=True): """Get a Storage instance for a credential. Args: filename: The JSON file storing a set of credentials client_id: The client_id for the credential user_agent: The user agent for the credential scope: string or iterable of strings, Scope(s) being requested warn_on_readonly: if True, log a warning if the store is readonly Returns: An object derived from client.Storage for getting/setting the credential. """ # Recreate the legacy key with these specific parameters key = {'clientId': client_id, 'userAgent': user_agent, 'scope': util.scopes_to_string(scope)} return get_credential_storage_custom_key( filename, key, warn_on_readonly=warn_on_readonly) @util.positional(2) def get_credential_storage_custom_string_key( filename, key_string, warn_on_readonly=True): """Get a Storage instance for a credential using a single string as a key. Allows you to provide a string as a custom key that will be used for credential storage and retrieval. Args: filename: The JSON file storing a set of credentials key_string: A string to use as the key for storing this credential. warn_on_readonly: if True, log a warning if the store is readonly Returns: An object derived from client.Storage for getting/setting the credential. """ # Create a key dictionary that can be used key_dict = {'key': key_string} return get_credential_storage_custom_key( filename, key_dict, warn_on_readonly=warn_on_readonly) @util.positional(2) def get_credential_storage_custom_key( filename, key_dict, warn_on_readonly=True): """Get a Storage instance for a credential using a dictionary as a key. Allows you to provide a dictionary as a custom key that will be used for credential storage and retrieval. Args: filename: The JSON file storing a set of credentials key_dict: A dictionary to use as the key for storing this credential. There is no ordering of the keys in the dictionary. Logically equivalent dictionaries will produce equivalent storage keys. warn_on_readonly: if True, log a warning if the store is readonly Returns: An object derived from client.Storage for getting/setting the credential. """ multistore = _get_multistore(filename, warn_on_readonly=warn_on_readonly) key = util.dict_to_tuple_key(key_dict) return multistore._get_storage(key) @util.positional(1) def get_all_credential_keys(filename, warn_on_readonly=True): """Gets all the registered credential keys in the given Multistore. Args: filename: The JSON file storing a set of credentials warn_on_readonly: if True, log a warning if the store is readonly Returns: A list of the credential keys present in the file. They are returned as dictionaries that can be passed into get_credential_storage_custom_key to get the actual credentials. """ multistore = _get_multistore(filename, warn_on_readonly=warn_on_readonly) multistore._lock() try: return multistore._get_all_credential_keys() finally: multistore._unlock() @util.positional(1) def _get_multistore(filename, warn_on_readonly=True): """A helper method to initialize the multistore with proper locking. Args: filename: The JSON file storing a set of credentials warn_on_readonly: if True, log a warning if the store is readonly Returns: A multistore object """ filename = os.path.expanduser(filename) _multistores_lock.acquire() try: multistore = _multistores.setdefault( filename, _MultiStore(filename, warn_on_readonly=warn_on_readonly)) finally: _multistores_lock.release() return multistore class _MultiStore(object): """A file backed store for multiple credentials.""" @util.positional(2) def __init__(self, filename, warn_on_readonly=True): """Initialize the class. This will create the file if necessary. """ self._file = LockedFile(filename, 'r+b', 'rb') self._thread_lock = threading.Lock() self._read_only = False self._warn_on_readonly = warn_on_readonly self._create_file_if_needed() # Cache of deserialized store. This is only valid after the # _MultiStore is locked or _refresh_data_cache is called. This is # of the form of: # # ((key, value), (key, value)...) -> OAuth2Credential # # If this is None, then the store hasn't been read yet. self._data = None class _Storage(BaseStorage): """A Storage object that knows how to read/write a single credential.""" def __init__(self, multistore, key): self._multistore = multistore self._key = key def acquire_lock(self): """Acquires any lock necessary to access this Storage. This lock is not reentrant. """ self._multistore._lock() def release_lock(self): """Release the Storage lock. Trying to release a lock that isn't held will result in a RuntimeError. """ self._multistore._unlock() def locked_get(self): """Retrieve credential. The Storage lock must be held when this is called. Returns: oauth2client.client.Credentials """ credential = self._multistore._get_credential(self._key) if credential: credential.set_store(self) return credential def locked_put(self, credentials): """Write a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store. """ self._multistore._update_credential(self._key, credentials) def locked_delete(self): """Delete a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store. """ self._multistore._delete_credential(self._key) def _create_file_if_needed(self): """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. """ if not os.path.exists(self._file.filename()): old_umask = os.umask(0177) try: open(self._file.filename(), 'a+b').close() finally: os.umask(old_umask) def _lock(self): """Lock the entire multistore.""" self._thread_lock.acquire() self._file.open_and_lock() if not self._file.is_locked(): self._read_only = True if self._warn_on_readonly: logger.warn('The credentials file (%s) is not writable. Opening in ' 'read-only mode. Any refreshed credentials will only be ' 'valid for this run.' % self._file.filename()) if os.path.getsize(self._file.filename()) == 0: logger.debug('Initializing empty multistore file') # The multistore is empty so write out an empty file. self._data = {} self._write() elif not self._read_only or self._data is None: # Only refresh the data if we are read/write or we haven't # cached the data yet. If we are readonly, we assume is isn't # changing out from under us and that we only have to read it # once. This prevents us from whacking any new access keys that # we have cached in memory but were unable to write out. self._refresh_data_cache() def _unlock(self): """Release the lock on the multistore.""" self._file.unlock_and_close() self._thread_lock.release() def _locked_json_read(self): """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. """ assert self._thread_lock.locked() self._file.file_handle().seek(0) return simplejson.load(self._file.file_handle()) def _locked_json_write(self, data): """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. """ assert self._thread_lock.locked() if self._read_only: return self._file.file_handle().seek(0) simplejson.dump(data, self._file.file_handle(), sort_keys=True, indent=2) self._file.file_handle().truncate() def _refresh_data_cache(self): """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. """ 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 Exception: logger.warn('Missing version for credential data store. It may be ' 'corrupt or an old version. Overwriting.') if version > 1: raise NewerCredentialStoreError( 'Credential file has file_version of %d. ' 'Only file_version of 1 is supported.' % version) credentials = [] try: credentials = raw_data['data'] except (TypeError, KeyError): pass for cred_entry in credentials: try: (key, credential) = self._decode_credential_from_json(cred_entry) self._data[key] = credential except: # If something goes wrong loading a credential, just ignore it logger.info('Error decoding credential, skipping', exc_info=True) def _decode_credential_from_json(self, cred_entry): """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. """ raw_key = cred_entry['key'] key = util.dict_to_tuple_key(raw_key) credential = None credential = Credentials.new_from_json(simplejson.dumps(cred_entry['credential'])) return (key, credential) def _write(self): """Write the cached data back out. The multistore must be locked. """ raw_data = {'file_version': 1} raw_creds = [] raw_data['data'] = raw_creds for (cred_key, cred) in self._data.items(): raw_key = dict(cred_key) raw_cred = simplejson.loads(cred.to_json()) raw_creds.append({'key': raw_key, 'credential': raw_cred}) self._locked_json_write(raw_data) def _get_all_credential_keys(self): """Gets all the registered credential keys in the multistore. Returns: A list of dictionaries corresponding to all the keys currently registered """ return [dict(key) for key in self._data.keys()] def _get_credential(self, key): """Get a credential from the multistore. The multistore must be locked. Args: key: The key used to retrieve the credential Returns: The credential specified or None if not present """ return self._data.get(key, None) def _update_credential(self, key, cred): """Update a credential and write the multistore. This must be called when the multistore is locked. Args: key: The key used to retrieve the credential cred: The OAuth2Credential to update/set """ self._data[key] = cred self._write() def _delete_credential(self, key): """Delete a credential and write the multistore. This must be called when the multistore is locked. Args: key: The key used to retrieve the credential """ try: del self._data[key] except KeyError: pass self._write() def _get_storage(self, key): """Get a Storage object to get/set a credential. This Storage is a 'view' into the multistore. Args: key: The key used to retrieve the credential Returns: A Storage object that can be used to get/set this cred """ return self._Storage(self, key) google-api-python-client-1.2/oauth2client/client.py0000640017135500116100000012637212173557443023377 0ustar jcgregorioeng00000000000000# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """An OAuth 2.0 client. Tools for interacting with OAuth 2.0 protected resources. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import base64 import clientsecrets import copy import datetime import httplib2 import logging import os import sys import time import urllib import urlparse from oauth2client import GOOGLE_AUTH_URI from oauth2client import GOOGLE_REVOKE_URI from oauth2client import GOOGLE_TOKEN_URI from oauth2client import util from oauth2client.anyjson import simplejson HAS_OPENSSL = False HAS_CRYPTO = False try: from oauth2client import crypt HAS_CRYPTO = True if crypt.OpenSSLVerifier is not None: HAS_OPENSSL = True except ImportError: pass try: from urlparse import parse_qsl except ImportError: from cgi import parse_qsl logger = logging.getLogger(__name__) # Expiry is stored in RFC3339 UTC format EXPIRY_FORMAT = '%Y-%m-%dT%H:%M:%SZ' # Which certs to use to validate id_tokens received. ID_TOKEN_VERIFICATON_CERTS = 'https://www.googleapis.com/oauth2/v1/certs' # Constant to use for the out of band OAuth 2.0 flow. OOB_CALLBACK_URN = 'urn:ietf:wg:oauth:2.0:oob' # Google Data client libraries may need to set this to [401, 403]. REFRESH_STATUS_CODES = [401] class Error(Exception): """Base error for this module.""" class FlowExchangeError(Error): """Error trying to exchange an authorization grant for an access token.""" class AccessTokenRefreshError(Error): """Error trying to refresh an expired access token.""" class TokenRevokeError(Error): """Error trying to revoke a token.""" class UnknownClientSecretsFlowError(Error): """The client secrets file called for an unknown type of OAuth 2.0 flow. """ class AccessTokenCredentialsError(Error): """Having only the access_token means no refresh is possible.""" class VerifyJwtTokenError(Error): """Could on retrieve certificates for validation.""" class NonAsciiHeaderError(Error): """Header names and values must be ASCII strings.""" def _abstract(): raise NotImplementedError('You need to override this function') class MemoryCache(object): """httplib2 Cache implementation which only caches locally.""" def __init__(self): self.cache = {} def get(self, key): return self.cache.get(key) def set(self, key, value): self.cache[key] = value def delete(self, key): self.cache.pop(key, None) class Credentials(object): """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 Credentials object. """ NON_SERIALIZED_MEMBERS = ['store'] def authorize(self, http): """Take an httplib2.Http instance (or equivalent) and authorizes it. 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. Args: http: httplib2.Http, an http object to be used to make the refresh request. """ _abstract() def refresh(self, http): """Forces a refresh of the access_token. Args: http: httplib2.Http, an http object to be used to make the refresh request. """ _abstract() def revoke(self, http): """Revokes a refresh_token and makes the credentials void. Args: http: httplib2.Http, an http object to be used to make the revoke request. """ _abstract() def apply(self, headers): """Add the authorization to the headers. Args: headers: dict, the headers to add the Authorization header to. """ _abstract() def _to_json(self, strip): """Utility function that creates JSON repr. of a Credentials object. 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(). """ t = type(self) d = copy.copy(self.__dict__) for member in strip: if member in d: del d[member] if 'token_expiry' in d and isinstance(d['token_expiry'], datetime.datetime): d['token_expiry'] = d['token_expiry'].strftime(EXPIRY_FORMAT) # Add in information we will need later to reconsistitue this instance. d['_class'] = t.__name__ d['_module'] = t.__module__ return simplejson.dumps(d) def to_json(self): """Creating a JSON representation of an instance of Credentials. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ return self._to_json(Credentials.NON_SERIALIZED_MEMBERS) @classmethod def new_from_json(cls, s): """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 = simplejson.loads(s) # Find and call the right classmethod from_json() to restore the object. module = data['_module'] try: m = __import__(module) except ImportError: # In case there's an object from the old package structure, update it module = module.replace('.apiclient', '') m = __import__(module) m = __import__(module, fromlist=module.split('.')[:-1]) kls = getattr(m, data['_class']) from_json = getattr(kls, 'from_json') return from_json(s) @classmethod def from_json(cls, s): """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. """ return Credentials() class Flow(object): """Base class for all Flow objects.""" pass class Storage(object): """Base class for all Storage objects. Store and retrieve a single credential. This class supports locking such that multiple processes and threads can operate on a single store. """ def acquire_lock(self): """Acquires any lock necessary to access this Storage. This lock is not reentrant. """ pass def release_lock(self): """Release the Storage lock. Trying to release a lock that isn't held will result in a RuntimeError. """ pass def locked_get(self): """Retrieve credential. The Storage lock must be held when this is called. Returns: oauth2client.client.Credentials """ _abstract() def locked_put(self, credentials): """Write a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store. """ _abstract() def locked_delete(self): """Delete a credential. The Storage lock must be held when this is called. """ _abstract() def get(self): """Retrieve credential. The Storage lock must *not* be held when this is called. Returns: oauth2client.client.Credentials """ self.acquire_lock() try: return self.locked_get() finally: self.release_lock() def put(self, credentials): """Write a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store. """ self.acquire_lock() try: self.locked_put(credentials) finally: self.release_lock() def delete(self): """Delete credential. Frees any resources associated with storing the credential. The Storage lock must *not* be held when this is called. Returns: None """ self.acquire_lock() try: return self.locked_delete() finally: self.release_lock() def clean_headers(headers): """Forces header keys and values to be strings, i.e not unicode. The httplib module just concats the header keys and values in a way that may make the message header a unicode string, which, if it then tries to contatenate to a binary request body may result in a unicode decode error. Args: headers: dict, A dictionary of headers. Returns: The same dictionary but with all the keys converted to strings. """ clean = {} try: for k, v in headers.iteritems(): clean[str(k)] = str(v) except UnicodeEncodeError: raise NonAsciiHeaderError(k + ': ' + v) return clean def _update_query_params(uri, params): """Updates a URI with new query parameters. Args: uri: string, A valid URI, with potential existing query parameters. params: dict, A dictionary of query parameters. Returns: The same URI but with the new query parameters added. """ parts = list(urlparse.urlparse(uri)) query_params = dict(parse_qsl(parts[4])) # 4 is the index of the query part query_params.update(params) parts[4] = urllib.urlencode(query_params) return urlparse.urlunparse(parts) class OAuth2Credentials(Credentials): """Credentials object for OAuth 2.0. Credentials can be applied to an httplib2.Http object using the authorize() method, which then adds the OAuth 2.0 access token to each request. OAuth2Credentials objects may be safely pickled and unpickled. """ @util.positional(8) def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=None, id_token=None, token_response=None): """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, refresh token. token_expiry: datetime, when the access_token expires. token_uri: string, URI of token endpoint. user_agent: string, The HTTP User-Agent to provide for this application. revoke_uri: string, URI for revoke endpoint. Defaults to None; a token can't be revoked if this is None. id_token: object, The identity of the resource owner. token_response: dict, the decoded response to the token request. None if a token hasn't been requested yet. Stored because some providers (e.g. wordpress.com) include extra fields that clients may want. Notes: store: callable, A callable that when passed a Credential will store the credential back to where it came from. This is needed to store the latest access_token if it has expired and been refreshed. """ 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.revoke_uri = revoke_uri self.id_token = id_token self.token_response = token_response # True if the credentials have been revoked or expired and can't be # refreshed. self.invalid = False def authorize(self, http): """Authorize an httplib2.Http instance with these credentials. The modified http.request method will add authentication headers to each request and will refresh access_tokens when a 401 is received on a request. In addition the http.request method has a credentials property, http.request.credentials, which is the Credentials object that authorized it. 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()'. """ request_orig = http.request # The closure that will replace 'httplib2.Http.request'. @util.positional(1) 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(request_orig) # Modify the request headers to add the appropriate # Authorization header. if headers is None: headers = {} self.apply(headers) if self.user_agent is not None: if 'user-agent' in headers: headers['user-agent'] = self.user_agent + ' ' + headers['user-agent'] else: headers['user-agent'] = self.user_agent resp, content = request_orig(uri, method, body, clean_headers(headers), redirections, connection_type) if resp.status in REFRESH_STATUS_CODES: logger.info('Refreshing due to a %s' % str(resp.status)) self._refresh(request_orig) self.apply(headers) return request_orig(uri, method, body, clean_headers(headers), redirections, connection_type) else: return (resp, content) # Replace the request method with our own closure. http.request = new_request # Set credentials as a property of the request method. setattr(http.request, 'credentials', self) return http def refresh(self, http): """Forces a refresh of the access_token. Args: http: httplib2.Http, an http object to be used to make the refresh request. """ self._refresh(http.request) def revoke(self, http): """Revokes a refresh_token and makes the credentials void. Args: http: httplib2.Http, an http object to be used to make the revoke request. """ self._revoke(http.request) def apply(self, headers): """Add the authorization to the headers. Args: headers: dict, the headers to add the Authorization header to. """ headers['Authorization'] = 'Bearer ' + self.access_token def to_json(self): return self._to_json(Credentials.NON_SERIALIZED_MEMBERS) @classmethod def from_json(cls, s): """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. """ 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 = cls( data['access_token'], data['client_id'], data['client_secret'], data['refresh_token'], data['token_expiry'], data['token_uri'], data['user_agent'], revoke_uri=data.get('revoke_uri', None), id_token=data.get('id_token', None), token_response=data.get('token_response', None)) retval.invalid = data['invalid'] return retval @property def access_token_expired(self): """True if the credential is expired or invalid. If the token_expiry isn't set, we assume the token doesn't expire. """ 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 def 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. """ self.store = store def _updateFromCredential(self, other): """Update this Credential from another instance.""" self.__dict__.update(other.__getstate__()) def __getstate__(self): """Trim the state down to something that can be pickled.""" d = copy.copy(self.__dict__) del d['store'] return d def __setstate__(self, state): """Reconstitute the state of the object from being pickled.""" self.__dict__.update(state) self.store = None def _generate_refresh_request_body(self): """Generate the body that will be used in the refresh request.""" body = urllib.urlencode({ 'grant_type': 'refresh_token', 'client_id': self.client_id, 'client_secret': self.client_secret, 'refresh_token': self.refresh_token, }) return body def _generate_refresh_request_headers(self): """Generate the headers that will be used in the refresh request.""" headers = { 'content-type': 'application/x-www-form-urlencoded', } if self.user_agent is not None: headers['user-agent'] = self.user_agent return headers def _refresh(self, http_request): """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. Args: http_request: callable, a callable that matches the method signature of httplib2.Http.request, used to make the refresh request. Raises: AccessTokenRefreshError: When the refresh fails. """ 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 access_token read from Storage') self._updateFromCredential(new_cred) else: self._do_refresh_request(http_request) finally: self.store.release_lock() def _do_refresh_request(self, http_request): """Refresh the access_token using the refresh_token. Args: http_request: callable, a callable that matches the method signature of httplib2.Http.request, used to make the refresh request. Raises: AccessTokenRefreshError: When the refresh fails. """ body = self._generate_refresh_request_body() headers = self._generate_refresh_request_headers() logger.info('Refreshing access_token') resp, content = http_request( self.token_uri, method='POST', body=body, headers=headers) if resp.status == 200: # TODO(jcgregorio) Raise an error if loads fails? d = simplejson.loads(content) self.token_response = d self.access_token = d['access_token'] self.refresh_token = d.get('refresh_token', self.refresh_token) if 'expires_in' in d: self.token_expiry = datetime.timedelta( seconds=int(d['expires_in'])) + datetime.datetime.utcnow() else: self.token_expiry = None if self.store: self.store.locked_put(self) else: # An {'error':...} response body means the token is expired or revoked, # so we flag the credentials as such. logger.info('Failed to retrieve access token: %s' % content) error_msg = 'Invalid response %s.' % resp['status'] try: d = simplejson.loads(content) if 'error' in d: error_msg = d['error'] self.invalid = True if self.store: self.store.locked_put(self) except StandardError: pass raise AccessTokenRefreshError(error_msg) def _revoke(self, http_request): """Revokes the refresh_token and deletes the store if available. Args: http_request: callable, a callable that matches the method signature of httplib2.Http.request, used to make the revoke request. """ self._do_revoke(http_request, self.refresh_token) def _do_revoke(self, http_request, token): """Revokes the credentials and deletes the store if available. Args: http_request: callable, a callable that matches the method signature of httplib2.Http.request, used to make the refresh request. token: A string used as the token to be revoked. Can be either an access_token or refresh_token. Raises: TokenRevokeError: If the revoke request does not return with a 200 OK. """ logger.info('Revoking token') query_params = {'token': token} token_revoke_uri = _update_query_params(self.revoke_uri, query_params) resp, content = http_request(token_revoke_uri) if resp.status == 200: self.invalid = True else: error_msg = 'Invalid response %s.' % resp.status try: d = simplejson.loads(content) if 'error' in d: error_msg = d['error'] except StandardError: pass raise TokenRevokeError(error_msg) if self.store: self.store.delete() class AccessTokenCredentials(OAuth2Credentials): """Credentials object for OAuth 2.0. Credentials can be applied to an httplib2.Http object using the authorize() method, which then signs each request from that object with the OAuth 2.0 access token. This set of credentials is for the use case where you have acquired an OAuth 2.0 access_token from another place such as a JavaScript client or another web application, and wish to use it from Python. Because only the access_token is present it can not be refreshed and will in time expire. AccessTokenCredentials objects may be safely pickled and unpickled. Usage: credentials = AccessTokenCredentials('', 'my-user-agent/1.0') http = httplib2.Http() http = credentials.authorize(http) Exceptions: AccessTokenCredentialsExpired: raised when the access_token expires or is revoked. """ def __init__(self, access_token, user_agent, revoke_uri=None): """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. revoke_uri: string, URI for revoke endpoint. Defaults to None; a token can't be revoked if this is None. """ super(AccessTokenCredentials, self).__init__( access_token, None, None, None, None, None, user_agent, revoke_uri=revoke_uri) @classmethod def from_json(cls, s): data = simplejson.loads(s) retval = AccessTokenCredentials( data['access_token'], data['user_agent']) return retval def _refresh(self, http_request): raise AccessTokenCredentialsError( 'The access_token is expired or invalid and can\'t be refreshed.') def _revoke(self, http_request): """Revokes the access_token and deletes the store if available. Args: http_request: callable, a callable that matches the method signature of httplib2.Http.request, used to make the revoke request. """ self._do_revoke(http_request, self.access_token) class AssertionCredentials(OAuth2Credentials): """Abstract Credentials object used for OAuth 2.0 assertion grants. 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. It must be subclassed to generate the appropriate assertion string. AssertionCredentials objects may be safely pickled and unpickled. """ @util.positional(2) def __init__(self, assertion_type, user_agent=None, token_uri=GOOGLE_TOKEN_URI, revoke_uri=GOOGLE_REVOKE_URI, **unused_kwargs): """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 can be used. revoke_uri: string, URI for revoke endpoint. """ super(AssertionCredentials, self).__init__( None, None, None, None, None, token_uri, user_agent, revoke_uri=revoke_uri) self.assertion_type = assertion_type def _generate_refresh_request_body(self): assertion = self._generate_assertion() body = urllib.urlencode({ 'assertion': assertion, 'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer', }) return body def _generate_assertion(self): """Generate the assertion string that will be used in the access token request. """ _abstract() def _revoke(self, http_request): """Revokes the access_token and deletes the store if available. Args: http_request: callable, a callable that matches the method signature of httplib2.Http.request, used to make the revoke request. """ self._do_revoke(http_request, self.access_token) if HAS_CRYPTO: # PyOpenSSL and PyCrypto are not prerequisites for oauth2client, so if it is # missing then don't create the SignedJwtAssertionCredentials or the # verify_id_token() method. class SignedJwtAssertionCredentials(AssertionCredentials): """Credentials object used for OAuth 2.0 Signed JWT assertion grants. 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. SignedJwtAssertionCredentials requires either PyOpenSSL, or PyCrypto 2.6 or later. For App Engine you may also consider using AppAssertionCredentials. """ MAX_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds @util.positional(4) def __init__(self, service_account_name, private_key, scope, private_key_password='notasecret', user_agent=None, token_uri=GOOGLE_TOKEN_URI, revoke_uri=GOOGLE_REVOKE_URI, **kwargs): """Constructor for SignedJwtAssertionCredentials. Args: service_account_name: string, id for account, usually an email address. private_key: string, private key in PKCS12 or PEM format. scope: string or iterable of strings, scope(s) of the credentials being requested. private_key_password: string, password for private_key, unused if private_key is in PEM format. user_agent: string, 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 can be used. revoke_uri: string, URI for revoke endpoint. kwargs: kwargs, Additional parameters to add to the JWT token, for example sub=joe@xample.org.""" super(SignedJwtAssertionCredentials, self).__init__( None, user_agent=user_agent, token_uri=token_uri, revoke_uri=revoke_uri, ) self.scope = util.scopes_to_string(scope) # Keep base64 encoded so it can be stored in JSON. self.private_key = base64.b64encode(private_key) self.private_key_password = private_key_password self.service_account_name = service_account_name self.kwargs = kwargs @classmethod def from_json(cls, s): data = simplejson.loads(s) retval = SignedJwtAssertionCredentials( data['service_account_name'], base64.b64decode(data['private_key']), data['scope'], private_key_password=data['private_key_password'], user_agent=data['user_agent'], token_uri=data['token_uri'], **data['kwargs'] ) retval.invalid = data['invalid'] retval.access_token = data['access_token'] return retval def _generate_assertion(self): """Generate the assertion that will be used in the request.""" now = long(time.time()) payload = { 'aud': self.token_uri, 'scope': self.scope, 'iat': now, 'exp': now + SignedJwtAssertionCredentials.MAX_TOKEN_LIFETIME_SECS, 'iss': self.service_account_name } payload.update(self.kwargs) logger.debug(str(payload)) private_key = base64.b64decode(self.private_key) return crypt.make_signed_jwt(crypt.Signer.from_string( private_key, self.private_key_password), payload) # Only used in verify_id_token(), which is always calling to the same URI # for the certs. _cached_http = httplib2.Http(MemoryCache()) @util.positional(2) def verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATON_CERTS): """Verifies a signed JWT id_token. This function requires PyOpenSSL and because of that it does not work on App Engine. Args: id_token: string, A Signed JWT. audience: string, The audience 'aud' that the token should be for. http: httplib2.Http, instance to use to make the HTTP request. Callers should supply an instance that has caching enabled. cert_uri: string, URI of the certificates in JSON format to verify the JWT against. Returns: The deserialized JSON in the JWT. Raises: oauth2client.crypt.AppIdentityError if the JWT fails to verify. """ if http is None: http = _cached_http resp, content = http.request(cert_uri) if resp.status == 200: certs = simplejson.loads(content) return crypt.verify_signed_jwt_with_certs(id_token, certs, audience) else: raise VerifyJwtTokenError('Status code: %d' % resp.status) def _urlsafe_b64decode(b64string): # Guard against unicode strings, which base64 can't handle. b64string = b64string.encode('ascii') padded = b64string + '=' * (4 - len(b64string) % 4) return base64.urlsafe_b64decode(padded) def _extract_id_token(id_token): """Extract the JSON payload from a JWT. Does the extraction w/o checking the signature. Args: id_token: string, OAuth 2.0 id_token. Returns: object, The deserialized JSON payload. """ segments = id_token.split('.') if (len(segments) != 3): raise VerifyJwtTokenError( 'Wrong number of segments in token: %s' % id_token) return simplejson.loads(_urlsafe_b64decode(segments[1])) def _parse_exchange_token_response(content): """Parses response of an exchange token request. Most providers return JSON but some (e.g. Facebook) return a url-encoded string. Args: content: The body of a response Returns: Content as a dictionary object. Note that the dict could be empty, i.e. {}. That basically indicates a failure. """ resp = {} try: resp = simplejson.loads(content) except StandardError: # different JSON libs raise different exceptions, # so we just do a catch-all here resp = dict(parse_qsl(content)) # some providers respond with 'expires', others with 'expires_in' if resp and 'expires' in resp: resp['expires_in'] = resp.pop('expires') return resp @util.positional(4) def credentials_from_code(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, user_agent=None, token_uri=GOOGLE_TOKEN_URI, auth_uri=GOOGLE_AUTH_URI, revoke_uri=GOOGLE_REVOKE_URI): """Exchanges an authorization code for an OAuth2Credentials object. Args: client_id: string, client identifier. client_secret: string, client secret. scope: string or iterable of strings, scope(s) to request. code: string, An authroization code, most likely passed down from the client redirect_uri: string, this is generally set to 'postmessage' to match the redirect_uri that the client specified http: httplib2.Http, optional http instance to use to do the fetch token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. auth_uri: string, URI for authorization endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. revoke_uri: string, URI for revoke endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. Returns: An OAuth2Credentials object. Raises: FlowExchangeError if the authorization code cannot be exchanged for an access token """ flow = OAuth2WebServerFlow(client_id, client_secret, scope, redirect_uri=redirect_uri, user_agent=user_agent, auth_uri=auth_uri, token_uri=token_uri, revoke_uri=revoke_uri) credentials = flow.step2_exchange(code, http=http) return credentials @util.positional(3) def credentials_from_clientsecrets_and_code(filename, scope, code, message = None, redirect_uri='postmessage', http=None, cache=None): """Returns OAuth2Credentials from a clientsecrets file and an auth code. Will create the right kind of Flow based on the contents of the clientsecrets file or will raise InvalidClientSecretsError for unknown types of Flows. Args: filename: string, File name of clientsecrets. scope: string or iterable of strings, scope(s) to request. code: string, An authorization code, most likely passed down from the client message: string, A friendly string to display to the user if the clientsecrets file is missing or invalid. If message is provided then sys.exit will be called in the case of an error. If message in not provided then clientsecrets.InvalidClientSecretsError will be raised. redirect_uri: string, this is generally set to 'postmessage' to match the redirect_uri that the client specified http: httplib2.Http, optional http instance to use to do the fetch cache: An optional cache service client that implements get() and set() methods. See clientsecrets.loadfile() for details. Returns: An OAuth2Credentials object. Raises: FlowExchangeError if the authorization code cannot be exchanged for an access token UnknownClientSecretsFlowError if the file describes an unknown kind of Flow. clientsecrets.InvalidClientSecretsError if the clientsecrets file is invalid. """ flow = flow_from_clientsecrets(filename, scope, message=message, cache=cache, redirect_uri=redirect_uri) credentials = flow.step2_exchange(code, http=http) return credentials class OAuth2WebServerFlow(Flow): """Does the Web Server Flow for OAuth 2.0. OAuth2WebServerFlow objects may be safely pickled and unpickled. """ @util.positional(4) def __init__(self, client_id, client_secret, scope, redirect_uri=None, user_agent=None, auth_uri=GOOGLE_AUTH_URI, token_uri=GOOGLE_TOKEN_URI, revoke_uri=GOOGLE_REVOKE_URI, **kwargs): """Constructor for OAuth2WebServerFlow. The kwargs argument is used to set extra query parameters on the auth_uri. For example, the access_type and approval_prompt query parameters can be set via kwargs. Args: client_id: string, client identifier. client_secret: string client secret. scope: string or iterable of strings, scope(s) of the credentials being requested. redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for a non-web-based application, or a URI that handles the callback from the authorization server. user_agent: string, HTTP User-Agent to provide for this application. 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. revoke_uri: string, URI for revoke endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. **kwargs: dict, The keyword arguments are all optional and required parameters for the OAuth calls. """ self.client_id = client_id self.client_secret = client_secret self.scope = util.scopes_to_string(scope) self.redirect_uri = redirect_uri self.user_agent = user_agent self.auth_uri = auth_uri self.token_uri = token_uri self.revoke_uri = revoke_uri self.params = { 'access_type': 'offline', 'response_type': 'code', } self.params.update(kwargs) @util.positional(1) def step1_get_authorize_url(self, redirect_uri=None): """Returns a URI to redirect to the provider. Args: redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for a non-web-based application, or a URI that handles the callback from the authorization server. This parameter is deprecated, please move to passing the redirect_uri in via the constructor. Returns: A URI as a string to redirect the user to begin the authorization flow. """ if redirect_uri is not None: logger.warning(('The redirect_uri parameter for' 'OAuth2WebServerFlow.step1_get_authorize_url is deprecated. Please' 'move to passing the redirect_uri in via the constructor.')) self.redirect_uri = redirect_uri if self.redirect_uri is None: raise ValueError('The value of redirect_uri must not be None.') query_params = { 'client_id': self.client_id, 'redirect_uri': self.redirect_uri, 'scope': self.scope, } query_params.update(self.params) return _update_query_params(self.auth_uri, query_params) @util.positional(2) def step2_exchange(self, code, http=None): """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 Returns: An OAuth2Credentials object that can be used to authorize requests. Raises: FlowExchangeError if a problem occured exchanging the code for a refresh_token. """ if not (isinstance(code, str) or isinstance(code, unicode)): if 'code' not in code: if 'error' in code: error_msg = code['error'] else: error_msg = 'No code was supplied in the query parameters.' raise FlowExchangeError(error_msg) else: 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-type': 'application/x-www-form-urlencoded', } if self.user_agent is not None: headers['user-agent'] = self.user_agent if http is None: http = httplib2.Http() resp, content = http.request(self.token_uri, method='POST', body=body, headers=headers) d = _parse_exchange_token_response(content) if resp.status == 200 and 'access_token' in d: access_token = d['access_token'] refresh_token = d.get('refresh_token', None) token_expiry = None if 'expires_in' in d: token_expiry = datetime.datetime.utcnow() + datetime.timedelta( seconds=int(d['expires_in'])) if 'id_token' in d: d['id_token'] = _extract_id_token(d['id_token']) logger.info('Successfully retrieved access token') return OAuth2Credentials(access_token, self.client_id, self.client_secret, refresh_token, token_expiry, self.token_uri, self.user_agent, revoke_uri=self.revoke_uri, id_token=d.get('id_token', None), token_response=d) else: logger.info('Failed to retrieve access token: %s' % content) if 'error' in d: # you never know what those providers got to say error_msg = unicode(d['error']) else: error_msg = 'Invalid response: %s.' % str(resp.status) raise FlowExchangeError(error_msg) @util.positional(2) def flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None): """Create a Flow from a clientsecrets file. Will create the right kind of Flow based on the contents of the clientsecrets file or will raise InvalidClientSecretsError for unknown types of Flows. Args: filename: string, File name of client secrets. scope: string or iterable of strings, scope(s) to request. redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for a non-web-based application, or a URI that handles the callback from the authorization server. message: string, A friendly string to display to the user if the clientsecrets file is missing or invalid. If message is provided then sys.exit will be called in the case of an error. If message in not provided then clientsecrets.InvalidClientSecretsError will be raised. cache: An optional cache service client that implements get() and set() methods. See clientsecrets.loadfile() for details. Returns: A Flow object. Raises: UnknownClientSecretsFlowError if the file describes an unknown kind of Flow. clientsecrets.InvalidClientSecretsError if the clientsecrets file is invalid. """ try: client_type, client_info = clientsecrets.loadfile(filename, cache=cache) if client_type in (clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED): constructor_kwargs = { 'redirect_uri': redirect_uri, 'auth_uri': client_info['auth_uri'], 'token_uri': client_info['token_uri'], } revoke_uri = client_info.get('revoke_uri') if revoke_uri is not None: constructor_kwargs['revoke_uri'] = revoke_uri return OAuth2WebServerFlow( client_info['client_id'], client_info['client_secret'], scope, **constructor_kwargs) except clientsecrets.InvalidClientSecretsError: if message: sys.exit(message) else: raise else: raise UnknownClientSecretsFlowError( 'This OAuth 2.0 flow is unsupported: %r' % client_type) google-api-python-client-1.2/oauth2client/xsrfutil.py0000640017135500116100000000645012173557443023773 0ustar jcgregorioeng00000000000000#!/usr/bin/python2.5 # # Copyright 2010 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Helper methods for creating & verifying XSRF tokens.""" __authors__ = [ '"Doug Coker" ', '"Joe Gregorio" ', ] import base64 import hmac import os # for urandom import time from oauth2client import util # Delimiter character DELIMITER = ':' # 1 hour in seconds DEFAULT_TIMEOUT_SECS = 1*60*60 @util.positional(2) def generate_token(key, user_id, action_id="", when=None): """Generates a URL-safe token for the given user, action, time tuple. Args: key: secret key to use. user_id: the user ID of the authenticated user. action_id: a string identifier of the action they requested authorization for. when: the time in seconds since the epoch at which the user was authorized for this action. If not set the current time is used. Returns: A string XSRF protection token. """ when = when or int(time.time()) digester = hmac.new(key) digester.update(str(user_id)) digester.update(DELIMITER) digester.update(action_id) digester.update(DELIMITER) digester.update(str(when)) digest = digester.digest() token = base64.urlsafe_b64encode('%s%s%d' % (digest, DELIMITER, when)) return token @util.positional(3) def validate_token(key, token, user_id, action_id="", current_time=None): """Validates that the given token authorizes the user for the action. Tokens are invalid if the time of issue is too old or if the token does not match what generateToken outputs (i.e. the token was forged). Args: key: secret key to use. token: a string of the token generated by generateToken. user_id: the user ID of the authenticated user. action_id: a string identifier of the action they requested authorization for. Returns: A boolean - True if the user is authorized for the action, False otherwise. """ if not token: return False try: decoded = base64.urlsafe_b64decode(str(token)) token_time = long(decoded.split(DELIMITER)[-1]) except (TypeError, ValueError): return False if current_time is None: current_time = time.time() # If the token is too old it's not valid. if current_time - token_time > DEFAULT_TIMEOUT_SECS: return False # The given token should match the generated one with the same time. expected_token = generate_token(key, user_id, action_id=action_id, when=token_time) if len(token) != len(expected_token): return False # Perform constant time comparison to avoid timing attacks different = 0 for x, y in zip(token, expected_token): different |= ord(x) ^ ord(y) if different: return False return True google-api-python-client-1.2/oauth2client/django_orm.py0000640017135500116100000000737112173557443024235 0ustar jcgregorioeng00000000000000# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """OAuth 2.0 utilities for Django. Utilities for using OAuth 2.0 in conjunction with the Django datastore. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import oauth2client import base64 import pickle from django.db import models from oauth2client.client import Storage as BaseStorage class CredentialsField(models.Field): __metaclass__ = models.SubfieldBase def __init__(self, *args, **kwargs): if 'null' not in kwargs: kwargs['null'] = True super(CredentialsField, self).__init__(*args, **kwargs) def get_internal_type(self): return "TextField" def to_python(self, value): if value is None: return None if isinstance(value, oauth2client.client.Credentials): return value return pickle.loads(base64.b64decode(value)) def get_db_prep_value(self, value, connection, prepared=False): if value is None: return None return base64.b64encode(pickle.dumps(value)) class FlowField(models.Field): __metaclass__ = models.SubfieldBase def __init__(self, *args, **kwargs): if 'null' not in kwargs: kwargs['null'] = True super(FlowField, self).__init__(*args, **kwargs) def get_internal_type(self): return "TextField" def to_python(self, value): if value is None: return None if isinstance(value, oauth2client.client.Flow): return value return pickle.loads(base64.b64decode(value)) def get_db_prep_value(self, value, connection, prepared=False): if value is None: return None return base64.b64encode(pickle.dumps(value)) class Storage(BaseStorage): """Store and retrieve a single credential to and from the datastore. This Storage helper presumes the Credentials have been stored as a CredenialsField on a db model class. """ def __init__(self, model_class, key_name, key_value, property_name): """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 """ self.model_class = model_class self.key_name = key_name self.key_value = key_value self.property_name = property_name def locked_get(self): """Retrieve Credential from datastore. Returns: oauth2client.Credentials """ 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) return credential def locked_put(self, credentials): """Write a Credentials to the datastore. Args: credentials: Credentials, the credentials to store. """ args = {self.key_name: self.key_value} entity = self.model_class(**args) setattr(entity, self.property_name, credentials) entity.save() def locked_delete(self): """Delete Credentials from the datastore.""" query = {self.key_name: self.key_value} entities = self.model_class.objects.filter(**query).delete() google-api-python-client-1.2/oauth2client/anyjson.py0000640017135500116100000000202412173557443023565 0ustar jcgregorioeng00000000000000# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utility module to import a JSON module Hides all the messy details of exactly where we get a simplejson module from. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' try: # pragma: no cover # Should work for Python2.6 and higher. import json as simplejson except ImportError: # pragma: no cover try: import simplejson except ImportError: # Try to import from django, should work on App Engine from django.utils import simplejson google-api-python-client-1.2/oauth2client/__init__.py0000640017135500116100000000032512173557443023645 0ustar jcgregorioeng00000000000000__version__ = "1.2" GOOGLE_AUTH_URI = 'https://accounts.google.com/o/oauth2/auth' GOOGLE_REVOKE_URI = 'https://accounts.google.com/o/oauth2/revoke' GOOGLE_TOKEN_URI = 'https://accounts.google.com/o/oauth2/token' google-api-python-client-1.2/oauth2client/appengine.py0000640017135500116100000007741412200460221024043 0ustar jcgregorioeng00000000000000# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for Google App Engine Utilities for making it easier to use OAuth 2.0 on Google App Engine. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import base64 import cgi import httplib2 import logging import os import pickle import threading import time from google.appengine.api import app_identity from google.appengine.api import memcache from google.appengine.api import users from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.ext.webapp.util import login_required from google.appengine.ext.webapp.util import run_wsgi_app from oauth2client import GOOGLE_AUTH_URI from oauth2client import GOOGLE_REVOKE_URI from oauth2client import GOOGLE_TOKEN_URI from oauth2client import clientsecrets from oauth2client import util from oauth2client import xsrfutil from oauth2client.anyjson import simplejson from oauth2client.client import AccessTokenRefreshError from oauth2client.client import AssertionCredentials from oauth2client.client import Credentials from oauth2client.client import Flow from oauth2client.client import OAuth2WebServerFlow from oauth2client.client import Storage # TODO(dhermes): Resolve import issue. # This is a temporary fix for a Google internal issue. try: from google.appengine.ext import ndb except ImportError: ndb = None logger = logging.getLogger(__name__) OAUTH2CLIENT_NAMESPACE = 'oauth2client#ns' XSRF_MEMCACHE_ID = 'xsrf_secret_key' def _safe_html(s): """Escape text to make it safe to display. Args: s: string, The text to escape. Returns: The escaped text as a string. """ return cgi.escape(s, quote=1).replace("'", ''') class InvalidClientSecretsError(Exception): """The client_secrets.json file is malformed or missing required fields.""" class InvalidXsrfTokenError(Exception): """The XSRF token is invalid or expired.""" class SiteXsrfSecretKey(db.Model): """Storage for the sites XSRF secret key. There will only be one instance stored of this model, the one used for the site. """ secret = db.StringProperty() if ndb is not None: class SiteXsrfSecretKeyNDB(ndb.Model): """NDB Model for storage for the sites XSRF secret key. Since this model uses the same kind as SiteXsrfSecretKey, it can be used interchangeably. This simply provides an NDB model for interacting with the same data the DB model interacts with. There should only be one instance stored of this model, the one used for the site. """ secret = ndb.StringProperty() @classmethod def _get_kind(cls): """Return the kind name for this class.""" return 'SiteXsrfSecretKey' def _generate_new_xsrf_secret_key(): """Returns a random XSRF secret key. """ return os.urandom(16).encode("hex") def xsrf_secret_key(): """Return the secret key for use for XSRF protection. If the Site entity does not have a secret key, this method will also create one and persist it. Returns: The secret key. """ secret = memcache.get(XSRF_MEMCACHE_ID, namespace=OAUTH2CLIENT_NAMESPACE) if not secret: # Load the one and only instance of SiteXsrfSecretKey. model = SiteXsrfSecretKey.get_or_insert(key_name='site') if not model.secret: model.secret = _generate_new_xsrf_secret_key() model.put() secret = model.secret memcache.add(XSRF_MEMCACHE_ID, secret, namespace=OAUTH2CLIENT_NAMESPACE) return str(secret) class AppAssertionCredentials(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. 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. """ @util.positional(2) def __init__(self, scope, **kwargs): """Constructor for AppAssertionCredentials Args: scope: string or iterable of strings, scope(s) of the credentials being requested. """ self.scope = util.scopes_to_string(scope) # Assertion type is no longer used, but still in the parent class signature. super(AppAssertionCredentials, self).__init__(None) @classmethod def from_json(cls, json): data = simplejson.loads(json) return AppAssertionCredentials(data['scope']) def _refresh(self, http_request): """Refreshes the access_token. Since the underlying App Engine app_identity implementation does its own caching we can skip all the storage hoops and just to a refresh using the API. Args: http_request: callable, a callable that matches the method signature of httplib2.Http.request, used to make the refresh request. Raises: AccessTokenRefreshError: When the refresh fails. """ try: scopes = self.scope.split() (token, _) = app_identity.get_access_token(scopes) except app_identity.Error, e: raise AccessTokenRefreshError(str(e)) self.access_token = token class FlowProperty(db.Property): """App Engine datastore Property for Flow. Utility property that allows easy storage and retrieval of an oauth2client.Flow""" # Tell what the user type is. data_type = Flow # For writing to datastore. def get_value_for_datastore(self, model_instance): flow = super(FlowProperty, self).get_value_for_datastore(model_instance) return db.Blob(pickle.dumps(flow)) # For reading from datastore. def make_value_from_datastore(self, value): if value is None: return None return pickle.loads(value) def validate(self, value): if value is not None and not isinstance(value, Flow): raise db.BadValueError('Property %s must be convertible ' 'to a FlowThreeLegged instance (%s)' % (self.name, value)) return super(FlowProperty, self).validate(value) def empty(self, value): return not value if ndb is not None: class FlowNDBProperty(ndb.PickleProperty): """App Engine NDB datastore Property for Flow. Serves the same purpose as the DB FlowProperty, but for NDB models. Since PickleProperty inherits from BlobProperty, the underlying representation of the data in the datastore will be the same as in the DB case. Utility property that allows easy storage and retrieval of an oauth2client.Flow """ def _validate(self, value): """Validates a value as a proper Flow object. Args: value: A value to be set on the property. Raises: TypeError if the value is not an instance of Flow. """ logger.info('validate: Got type %s', type(value)) if value is not None and not isinstance(value, Flow): raise TypeError('Property %s must be convertible to a flow ' 'instance; received: %s.' % (self._name, value)) class CredentialsProperty(db.Property): """App Engine datastore Property for Credentials. Utility property that allows easy storage and retrieval of oath2client.Credentials """ # Tell what the user type is. data_type = Credentials # For writing to datastore. def get_value_for_datastore(self, model_instance): logger.info("get: Got type " + str(type(model_instance))) cred = super(CredentialsProperty, self).get_value_for_datastore(model_instance) if cred is None: cred = '' else: cred = cred.to_json() return db.Blob(cred) # For reading from datastore. def make_value_from_datastore(self, value): logger.info("make: Got type " + str(type(value))) if value is None: return None if len(value) == 0: return None try: credentials = Credentials.new_from_json(value) except ValueError: credentials = None return credentials def validate(self, value): value = super(CredentialsProperty, self).validate(value) logger.info("validate: Got type " + str(type(value))) if value is not None and not isinstance(value, Credentials): raise db.BadValueError('Property %s must be convertible ' 'to a Credentials instance (%s)' % (self.name, value)) #if value is not None and not isinstance(value, Credentials): # return None return value if ndb is not None: # TODO(dhermes): Turn this into a JsonProperty and overhaul the Credentials # and subclass mechanics to use new_from_dict, to_dict, # from_dict, etc. class CredentialsNDBProperty(ndb.BlobProperty): """App Engine NDB datastore Property for Credentials. Serves the same purpose as the DB CredentialsProperty, but for NDB models. Since CredentialsProperty stores data as a blob and this inherits from BlobProperty, the data in the datastore will be the same as in the DB case. Utility property that allows easy storage and retrieval of Credentials and subclasses. """ def _validate(self, value): """Validates a value as a proper credentials object. Args: value: A value to be set on the property. Raises: TypeError if the value is not an instance of Credentials. """ logger.info('validate: Got type %s', type(value)) if value is not None and not isinstance(value, Credentials): raise TypeError('Property %s must be convertible to a credentials ' 'instance; received: %s.' % (self._name, value)) def _to_base_type(self, value): """Converts our validated value to a JSON serialized string. Args: value: A value to be set in the datastore. Returns: A JSON serialized version of the credential, else '' if value is None. """ if value is None: return '' else: return value.to_json() def _from_base_type(self, value): """Converts our stored JSON string back to the desired type. Args: value: A value from the datastore to be converted to the desired type. Returns: A deserialized Credentials (or subclass) object, else None if the value can't be parsed. """ if not value: return None try: # Uses the from_json method of the implied class of value credentials = Credentials.new_from_json(value) except ValueError: credentials = None return credentials class StorageByKeyName(Storage): """Store and retrieve a credential to and from the App Engine datastore. This Storage helper presumes the Credentials have been stored as a CredentialsProperty or CredentialsNDBProperty on a datastore model class, and that entities are stored by key_name. """ @util.positional(4) def __init__(self, model, key_name, property_name, cache=None, user=None): """Constructor for Storage. Args: model: db.Model or ndb.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 or CredentialsNDBProperty. cache: memcache, a write-through cache to put in front of the datastore. If the model you are using is an NDB model, using a cache will be redundant since the model uses an instance cache and memcache for you. user: users.User object, optional. Can be used to grab user ID as a key_name if no key name is specified. """ if key_name is None: if user is None: raise ValueError('StorageByKeyName called with no key name or user.') key_name = user.user_id() self._model = model self._key_name = key_name self._property_name = property_name self._cache = cache def _is_ndb(self): """Determine whether the model of the instance is an NDB model. Returns: Boolean indicating whether or not the model is an NDB or DB model. """ # issubclass will fail if one of the arguments is not a class, only need # worry about new-style classes since ndb and db models are new-style if isinstance(self._model, type): if ndb is not None and issubclass(self._model, ndb.Model): return True elif issubclass(self._model, db.Model): return False raise TypeError('Model class not an NDB or DB model: %s.' % (self._model,)) def _get_entity(self): """Retrieve entity from datastore. Uses a different model method for db or ndb models. Returns: Instance of the model corresponding to the current storage object and stored using the key name of the storage object. """ if self._is_ndb(): return self._model.get_by_id(self._key_name) else: return self._model.get_by_key_name(self._key_name) def _delete_entity(self): """Delete entity from datastore. Attempts to delete using the key_name stored on the object, whether or not the given key is in the datastore. """ if self._is_ndb(): ndb.Key(self._model, self._key_name).delete() else: entity_key = db.Key.from_path(self._model.kind(), self._key_name) db.delete(entity_key) def locked_get(self): """Retrieve Credential from datastore. Returns: oauth2client.Credentials """ credentials = None if self._cache: json = self._cache.get(self._key_name) if json: credentials = Credentials.new_from_json(json) if credentials is None: entity = self._get_entity() if entity is not None: credentials = getattr(entity, self._property_name) if self._cache: self._cache.set(self._key_name, credentials.to_json()) if credentials and hasattr(credentials, 'set_store'): credentials.set_store(self) return credentials def locked_put(self, credentials): """Write a Credentials to the datastore. Args: credentials: Credentials, the credentials to store. """ 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()) def locked_delete(self): """Delete Credential from datastore.""" if self._cache: self._cache.delete(self._key_name) self._delete_entity() class CredentialsModel(db.Model): """Storage for OAuth 2.0 Credentials Storage of the model is keyed by the user.user_id(). """ credentials = CredentialsProperty() if ndb is not None: class CredentialsNDBModel(ndb.Model): """NDB Model for storage of OAuth 2.0 Credentials Since this model uses the same kind as CredentialsModel and has a property which can serialize and deserialize Credentials correctly, it can be used interchangeably with a CredentialsModel to access, insert and delete the same entities. This simply provides an NDB model for interacting with the same data the DB model interacts with. Storage of the model is keyed by the user.user_id(). """ credentials = CredentialsNDBProperty() @classmethod def _get_kind(cls): """Return the kind name for this class.""" return 'CredentialsModel' def _build_state_value(request_handler, user): """Composes the value for the 'state' parameter. Packs the current request URI and an XSRF token into an opaque string that can be passed to the authentication server via the 'state' parameter. Args: request_handler: webapp.RequestHandler, The request. user: google.appengine.api.users.User, The current user. Returns: The state value as a string. """ uri = request_handler.request.url token = xsrfutil.generate_token(xsrf_secret_key(), user.user_id(), action_id=str(uri)) return uri + ':' + token def _parse_state_value(state, user): """Parse the value of the 'state' parameter. Parses the value and validates the XSRF token in the state parameter. Args: state: string, The value of the state parameter. user: google.appengine.api.users.User, The current user. Raises: InvalidXsrfTokenError: if the XSRF token is invalid. Returns: The redirect URI. """ uri, token = state.rsplit(':', 1) if not xsrfutil.validate_token(xsrf_secret_key(), token, user.user_id(), action_id=uri): raise InvalidXsrfTokenError() return uri class OAuth2Decorator(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/plus') 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 """ def set_credentials(self, credentials): self._tls.credentials = credentials def get_credentials(self): """A thread local Credentials object. Returns: A client.Credentials object, or None if credentials hasn't been set in this thread yet, which may happen when calling has_credentials inside oauth_aware. """ return getattr(self._tls, 'credentials', None) credentials = property(get_credentials, set_credentials) def set_flow(self, flow): self._tls.flow = flow def get_flow(self): """A thread local Flow object. Returns: A credentials.Flow object, or None if the flow hasn't been set in this thread yet, which happens in _create_flow() since Flows are created lazily. """ return getattr(self._tls, 'flow', None) flow = property(get_flow, set_flow) @util.positional(4) def __init__(self, client_id, client_secret, scope, auth_uri=GOOGLE_AUTH_URI, token_uri=GOOGLE_TOKEN_URI, revoke_uri=GOOGLE_REVOKE_URI, user_agent=None, message=None, callback_path='/oauth2callback', token_response_param=None, _storage_class=StorageByKeyName, _credentials_class=CredentialsModel, _credentials_property_name='credentials', **kwargs): """Constructor for OAuth2Decorator Args: client_id: string, client identifier. client_secret: string client secret. scope: string or iterable 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 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. revoke_uri: string, URI for revoke endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. user_agent: string, User agent of your application, default to None. message: Message to display if there are problems with the OAuth 2.0 configuration. The message may contain HTML and will be presented on the web interface for any method that uses the decorator. callback_path: string, The absolute path to use as the callback URI. Note that this must match up with the URI given when registering the application in the APIs Console. token_response_param: string. If provided, the full JSON response to the access token request will be encoded and included in this query parameter in the callback URI. This is useful with providers (e.g. wordpress.com) that include extra fields that the client may want. _storage_class: "Protected" keyword argument not typically provided to this constructor. A storage class to aid in storing a Credentials object for a user in the datastore. Defaults to StorageByKeyName. _credentials_class: "Protected" keyword argument not typically provided to this constructor. A db or ndb Model class to hold credentials. Defaults to CredentialsModel. _credentials_property_name: "Protected" keyword argument not typically provided to this constructor. A string indicating the name of the field on the _credentials_class where a Credentials object will be stored. Defaults to 'credentials'. **kwargs: dict, Keyword arguments are be passed along as kwargs to the OAuth2WebServerFlow constructor. """ self._tls = threading.local() self.flow = None self.credentials = None self._client_id = client_id self._client_secret = client_secret self._scope = util.scopes_to_string(scope) self._auth_uri = auth_uri self._token_uri = token_uri self._revoke_uri = revoke_uri self._user_agent = user_agent self._kwargs = kwargs self._message = message self._in_error = False self._callback_path = callback_path self._token_response_param = token_response_param self._storage_class = _storage_class self._credentials_class = _credentials_class self._credentials_property_name = _credentials_property_name def _display_error_message(self, request_handler): request_handler.response.out.write('') request_handler.response.out.write(_safe_html(self._message)) request_handler.response.out.write('') def 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. """ def check_oauth(request_handler, *args, **kwargs): if self._in_error: self._display_error_message(request_handler) return user = users.get_current_user() # Don't use @login_decorator as this could be used in a POST request. if not user: request_handler.redirect(users.create_login_url( request_handler.request.uri)) return self._create_flow(request_handler) # Store the request URI in 'state' so we can use it later self.flow.params['state'] = _build_state_value(request_handler, user) self.credentials = self._storage_class( self._credentials_class, None, self._credentials_property_name, user=user).get() if not self.has_credentials(): return request_handler.redirect(self.authorize_url()) try: resp = method(request_handler, *args, **kwargs) except AccessTokenRefreshError: return request_handler.redirect(self.authorize_url()) finally: self.credentials = None return resp return check_oauth def _create_flow(self, request_handler): """Create the Flow object. The Flow is calculated lazily since we don't know where this app is running until it receives a request, at which point redirect_uri can be calculated and then the Flow object can be constructed. Args: request_handler: webapp.RequestHandler, the request handler. """ if self.flow is None: redirect_uri = request_handler.request.relative_url( self._callback_path) # Usually /oauth2callback self.flow = OAuth2WebServerFlow(self._client_id, self._client_secret, self._scope, redirect_uri=redirect_uri, user_agent=self._user_agent, auth_uri=self._auth_uri, token_uri=self._token_uri, revoke_uri=self._revoke_uri, **self._kwargs) def 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. """ def setup_oauth(request_handler, *args, **kwargs): if self._in_error: self._display_error_message(request_handler) return user = users.get_current_user() # Don't use @login_decorator as this could be used in a POST request. if not user: request_handler.redirect(users.create_login_url( request_handler.request.uri)) return self._create_flow(request_handler) self.flow.params['state'] = _build_state_value(request_handler, user) self.credentials = self._storage_class( self._credentials_class, None, self._credentials_property_name, user=user).get() try: resp = method(request_handler, *args, **kwargs) finally: self.credentials = None return resp return setup_oauth def 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. """ return self.credentials is not None and not self.credentials.invalid def 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. """ url = self.flow.step1_get_authorize_url() return str(url) def 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. """ return self.credentials.authorize(httplib2.Http()) @property def callback_path(self): """The absolute path where the callback will occur. Note this is the absolute path, not the absolute URI, that will be calculated by the decorator at runtime. See callback_handler() for how this should be used. Returns: The callback path as a string. """ return self._callback_path def callback_handler(self): """RequestHandler for the OAuth 2.0 redirect callback. Usage: app = webapp.WSGIApplication([ ('/index', MyIndexHandler), ..., (decorator.callback_path, decorator.callback_handler()) ]) Returns: A webapp.RequestHandler that handles the redirect back from the server during the OAuth 2.0 dance. """ decorator = self class OAuth2Handler(webapp.RequestHandler): """Handler for the redirect_uri of the OAuth 2.0 dance.""" @login_required def get(self): error = self.request.get('error') if error: errormsg = self.request.get('error_description', error) self.response.out.write( 'The authorization request failed: %s' % _safe_html(errormsg)) else: user = users.get_current_user() decorator._create_flow(self) credentials = decorator.flow.step2_exchange(self.request.params) decorator._storage_class( decorator._credentials_class, None, decorator._credentials_property_name, user=user).put(credentials) redirect_uri = _parse_state_value(str(self.request.get('state')), user) if decorator._token_response_param and credentials.token_response: resp_json = simplejson.dumps(credentials.token_response) redirect_uri = util._add_query_parameter( redirect_uri, decorator._token_response_param, resp_json) self.redirect(redirect_uri) return OAuth2Handler def callback_application(self): """WSGI application for handling the OAuth 2.0 redirect callback. If you need finer grained control use `callback_handler` which returns just the webapp.RequestHandler. Returns: A webapp.WSGIApplication that handles the redirect back from the server during the OAuth 2.0 dance. """ return webapp.WSGIApplication([ (self.callback_path, self.callback_handler()) ]) class OAuth2DecoratorFromClientSecrets(OAuth2Decorator): """An OAuth2Decorator that builds from a clientsecrets file. Uses a clientsecrets file as the source for all the information when constructing an OAuth2Decorator. Example: decorator = OAuth2DecoratorFromClientSecrets( os.path.join(os.path.dirname(__file__), 'client_secrets.json') scope='https://www.googleapis.com/auth/plus') 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 """ @util.positional(3) def __init__(self, filename, scope, message=None, cache=None): """Constructor Args: filename: string, File name of client secrets. scope: string or iterable of strings, scope(s) of the credentials being requested. 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 decorator. cache: An optional cache service client that implements get() and set() methods. See clientsecrets.loadfile() for details. """ client_type, client_info = clientsecrets.loadfile(filename, cache=cache) if client_type not in [ clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED]: raise InvalidClientSecretsError( 'OAuth2Decorator doesn\'t support this OAuth 2.0 flow.') constructor_kwargs = { 'auth_uri': client_info['auth_uri'], 'token_uri': client_info['token_uri'], 'message': message, } revoke_uri = client_info.get('revoke_uri') if revoke_uri is not None: constructor_kwargs['revoke_uri'] = revoke_uri super(OAuth2DecoratorFromClientSecrets, self).__init__( client_info['client_id'], client_info['client_secret'], scope, **constructor_kwargs) if message is not None: self._message = message else: self._message = 'Please configure your application for OAuth 2.0.' @util.positional(2) def oauth2decorator_from_clientsecrets(filename, scope, message=None, cache=None): """Creates an OAuth2Decorator populated from a clientsecrets file. Args: filename: string, File name of client secrets. scope: string or list of strings, scope(s) of the credentials being requested. 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 decorator. cache: An optional cache service client that implements get() and set() methods. See clientsecrets.loadfile() for details. Returns: An OAuth2Decorator """ return OAuth2DecoratorFromClientSecrets(filename, scope, message=message, cache=cache) google-api-python-client-1.2/oauth2client/crypt.py0000640017135500116100000002377112173557443023261 0ustar jcgregorioeng00000000000000#!/usr/bin/python2.4 # -*- coding: utf-8 -*- # # Copyright (C) 2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import base64 import hashlib import logging import time from anyjson import simplejson CLOCK_SKEW_SECS = 300 # 5 minutes in seconds AUTH_TOKEN_LIFETIME_SECS = 300 # 5 minutes in seconds MAX_TOKEN_LIFETIME_SECS = 86400 # 1 day in seconds logger = logging.getLogger(__name__) class AppIdentityError(Exception): pass try: from OpenSSL import crypto class OpenSSLVerifier(object): """Verifies the signature on a message.""" def __init__(self, pubkey): """Constructor. Args: pubkey, OpenSSL.crypto.PKey, The public key to verify with. """ self._pubkey = pubkey def verify(self, message, signature): """Verifies a message against a signature. Args: message: string, The message to verify. signature: string, The signature on the message. Returns: True if message was signed by the private key associated with the public key that this object was constructed with. """ try: crypto.verify(self._pubkey, signature, message, 'sha256') return True except: return False @staticmethod def from_string(key_pem, is_x509_cert): """Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance. Raises: OpenSSL.crypto.Error if the key_pem can't be parsed. """ if is_x509_cert: pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem) else: pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem) return OpenSSLVerifier(pubkey) class OpenSSLSigner(object): """Signs messages with a private key.""" def __init__(self, pkey): """Constructor. Args: pkey, OpenSSL.crypto.PKey (or equiv), The private key to sign with. """ self._key = pkey def sign(self, message): """Signs a message. Args: message: string, Message to be signed. Returns: string, The signature of the message for the given key. """ return crypto.sign(self._key, message, 'sha256') @staticmethod def from_string(key, password='notasecret'): """Construct a Signer instance from a string. Args: key: string, private key in PKCS12 or PEM format. password: string, password for the private key file. Returns: Signer instance. Raises: OpenSSL.crypto.Error if the key can't be parsed. """ if key.startswith('-----BEGIN '): pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key) else: pkey = crypto.load_pkcs12(key, password).get_privatekey() return OpenSSLSigner(pkey) except ImportError: OpenSSLVerifier = None OpenSSLSigner = None try: from Crypto.PublicKey import RSA from Crypto.Hash import SHA256 from Crypto.Signature import PKCS1_v1_5 class PyCryptoVerifier(object): """Verifies the signature on a message.""" def __init__(self, pubkey): """Constructor. Args: pubkey, OpenSSL.crypto.PKey (or equiv), The public key to verify with. """ self._pubkey = pubkey def verify(self, message, signature): """Verifies a message against a signature. Args: message: string, The message to verify. signature: string, The signature on the message. Returns: True if message was signed by the private key associated with the public key that this object was constructed with. """ try: return PKCS1_v1_5.new(self._pubkey).verify( SHA256.new(message), signature) except: return False @staticmethod def from_string(key_pem, is_x509_cert): """Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance. Raises: NotImplementedError if is_x509_cert is true. """ if is_x509_cert: raise NotImplementedError( 'X509 certs are not supported by the PyCrypto library. ' 'Try using PyOpenSSL if native code is an option.') else: pubkey = RSA.importKey(key_pem) return PyCryptoVerifier(pubkey) class PyCryptoSigner(object): """Signs messages with a private key.""" def __init__(self, pkey): """Constructor. Args: pkey, OpenSSL.crypto.PKey (or equiv), The private key to sign with. """ self._key = pkey def sign(self, message): """Signs a message. Args: message: string, Message to be signed. Returns: string, The signature of the message for the given key. """ return PKCS1_v1_5.new(self._key).sign(SHA256.new(message)) @staticmethod def from_string(key, password='notasecret'): """Construct a Signer instance from a string. Args: key: string, private key in PEM format. password: string, password for private key file. Unused for PEM files. Returns: Signer instance. Raises: NotImplementedError if they key isn't in PEM format. """ if key.startswith('-----BEGIN '): pkey = RSA.importKey(key) else: raise NotImplementedError( 'PKCS12 format is not supported by the PyCrpto library. ' 'Try converting to a "PEM" ' '(openssl pkcs12 -in xxxxx.p12 -nodes -nocerts > privatekey.pem) ' 'or using PyOpenSSL if native code is an option.') return PyCryptoSigner(pkey) except ImportError: PyCryptoVerifier = None PyCryptoSigner = None if OpenSSLSigner: Signer = OpenSSLSigner Verifier = OpenSSLVerifier elif PyCryptoSigner: Signer = PyCryptoSigner Verifier = PyCryptoVerifier else: raise ImportError('No encryption library found. Please install either ' 'PyOpenSSL, or PyCrypto 2.6 or later') def _urlsafe_b64encode(raw_bytes): return base64.urlsafe_b64encode(raw_bytes).rstrip('=') def _urlsafe_b64decode(b64string): # Guard against unicode strings, which base64 can't handle. b64string = b64string.encode('ascii') padded = b64string + '=' * (4 - len(b64string) % 4) return base64.urlsafe_b64decode(padded) def _json_encode(data): return simplejson.dumps(data, separators = (',', ':')) def make_signed_jwt(signer, payload): """Make a signed JWT. See http://self-issued.info/docs/draft-jones-json-web-token.html. Args: signer: crypt.Signer, Cryptographic signer. payload: dict, Dictionary of data to convert to JSON and then sign. Returns: string, The JWT for the payload. """ header = {'typ': 'JWT', 'alg': 'RS256'} segments = [ _urlsafe_b64encode(_json_encode(header)), _urlsafe_b64encode(_json_encode(payload)), ] signing_input = '.'.join(segments) signature = signer.sign(signing_input) segments.append(_urlsafe_b64encode(signature)) logger.debug(str(segments)) return '.'.join(segments) def verify_signed_jwt_with_certs(jwt, certs, audience): """Verify a JWT against public certs. See http://self-issued.info/docs/draft-jones-json-web-token.html. Args: jwt: string, A JWT. certs: dict, Dictionary where values of public keys in PEM format. audience: string, The audience, 'aud', that this JWT should contain. If None then the JWT's 'aud' parameter is not verified. Returns: dict, The deserialized JSON payload in the JWT. Raises: AppIdentityError if any checks are failed. """ segments = jwt.split('.') if (len(segments) != 3): raise AppIdentityError( 'Wrong number of segments in token: %s' % jwt) signed = '%s.%s' % (segments[0], segments[1]) signature = _urlsafe_b64decode(segments[2]) # Parse token. json_body = _urlsafe_b64decode(segments[1]) try: parsed = simplejson.loads(json_body) except: raise AppIdentityError('Can\'t parse token: %s' % json_body) # Check signature. verified = False for (keyname, pem) in certs.items(): verifier = Verifier.from_string(pem, True) if (verifier.verify(signed, signature)): verified = True break if not verified: raise AppIdentityError('Invalid token signature: %s' % jwt) # Check creation timestamp. iat = parsed.get('iat') if iat is None: raise AppIdentityError('No iat field in token: %s' % json_body) earliest = iat - CLOCK_SKEW_SECS # Check expiration timestamp. now = long(time.time()) exp = parsed.get('exp') if exp is None: raise AppIdentityError('No exp field in token: %s' % json_body) if exp >= now + MAX_TOKEN_LIFETIME_SECS: raise AppIdentityError( 'exp field too far in future: %s' % json_body) latest = exp + CLOCK_SKEW_SECS if now < earliest: raise AppIdentityError('Token used too early, %d < %d: %s' % (now, earliest, json_body)) if now > latest: raise AppIdentityError('Token used too late, %d > %d: %s' % (now, latest, json_body)) # Check audience. if audience is not None: aud = parsed.get('aud') if aud is None: raise AppIdentityError('No aud field in token: %s' % json_body) if aud != audience: raise AppIdentityError('Wrong recipient, %s != %s: %s' % (aud, audience, json_body)) return parsed google-api-python-client-1.2/setup.py0000640017135500116100000000371212200460456020634 0ustar jcgregorioeng00000000000000# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Setup script for Google API Python client. Also installs included versions of third party libraries, if those libraries are not already installed. """ from setuptools import setup packages = [ 'apiclient', 'oauth2client', 'uritemplate', ] install_requires = [ 'httplib2>=0.8', ] needs_json = False try: import json except ImportError: try: import simplejson except ImportError: needs_json = True if needs_json: install_requires.append('simplejson') long_desc = """The Google API Client for Python is a client library for accessing the Plus, Moderator, and many other Google APIs.""" import apiclient version = apiclient.__version__ setup(name="google-api-python-client", version=version, description="Google API Client Library for Python", long_description=long_desc, author="Joe Gregorio", author_email="jcgregorio@google.com", url="http://code.google.com/p/google-api-python-client/", install_requires=install_requires, packages=packages, package_data={}, license="Apache 2.0", keywords="google api client", classifiers=['Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX', 'Topic :: Internet :: WWW/HTTP']) google-api-python-client-1.2/LICENSE0000640017135500116100000000136312173557442020142 0ustar jcgregorioeng00000000000000 Copyright (C) 2010-2012 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Dependent Modules ================= This code has the following dependencies above and beyond the Python standard library: uritemplates - Apache License 2.0 httplib2 - MIT License google-api-python-client-1.2/CHANGELOG0000640017135500116100000001503712173557442020352 0ustar jcgregorioeng00000000000000v1.2 Version 1.2 The use of the gflags library is now deprecated, and is no longer a dependency. If you are still using the oauth2client.tools.run() function then include gflags as a dependency of your application or switch to oauth2client.tools.run_flow. Samples have been updated to use the new apiclient.sample_tools, and no longer use gflags. Added support for the experimental Object Change Notification, as found in the Cloud Storage API. The oauth2client App Engine decorators are now threadsafe. - Use the following redirects feature of httplib2 where it returns the ultimate URL after a series of redirects to avoid multiple hops for every resumable media upload request. - Updated AdSense Management API samples to V1.3 - Add option to automatically retry requests. - Ability to list registered keys in multistore_file. - User-agent must contain (gzip). - The 'method' parameter for httplib2 is not positional. This would cause spurious warnings in the logging. - Making OAuth2Decorator more extensible. Fixes Issue 256. - Update AdExchange Buyer API examples to version v1.2. v1.1 Version 1.1 Add PEM support to SignedJWTAssertionCredentials (used to only support PKCS12 formatted keys). Note that if you use PEM formatted keys you can use PyCrypto 2.6 or later instead of OpenSSL. Allow deserialized discovery docs to be passed to build_from_document(). - Make ResumableUploadError derive from HttpError. - Many changes to move all the closures in apiclient.discovery into real - classes and objects. - Make from_json behavior inheritable. - Expose the full token response in OAuth2Client and OAuth2Decorator. - Handle reasons that are None. - Added support for NDB based storing of oauth2client objects. - Update grant_type for AssertionCredentials. - Adding a .revoke() to Credentials. Closes issue 98. - Modify oauth2client.multistore_file to store and retrieve credentials using an arbitrary key. - Don't accept 403 challenges by default for auth challenges. - Set httplib2.RETRIES to 1. - Consolidate handling of scopes. - Upgrade to httplib2 version 0.8. - Allow setting the response_type in OAuth2WebServerFlow. - Ensure that dataWrapper feature is checked before using the 'data' value. - HMAC verification does not use a constant time algorithm. v1.0 Version 1.0 - Changes to the code for running tests and building releases. v1.0c3 Version 1.0 Release Candidate 3 - In samples and oauth2 decorator, escape untrusted content before displaying it. - Do not allow credentials files to be symlinks. - Add XSRF protection to oauth2decorator callback 'state'. - Handle uploading chunked media by stream. - Handle passing streams directly to httplib2. - Add support for Google Compute Engine service accounts. - Flows no longer need to be saved between uses. - Change GET to POST if URI is too long. Fixes issue #96. - Add a keyring based Storage. - More robust picking up JSON error responses. - Make batch errors align with normal errors. - Add a Google Compute sample. - Token refresh to work with 'old' GData API - Loading of client_secrets JSON file backed by a cache. - Switch to new discovery path parameters. - Add support for additionalProperties when printing schema'd objects. - Fix media upload parameter names. Reviewed in http://codereview.appspot.com/6374062/ - oauth2client support for URL-encoded format of exchange token response (e.g. Facebook) - Build cleaner and easier to read docs for dynamic surfaces. v1.0c2 Version 1.0 Release Candidate 2 - Parameter values of None should be treated as missing. Fixes issue #144. - Distribute the samples separately from the library source. Fixes issue #155. - Move all remaining samples over to client_secrets.json. Fixes issue #156. - Make locked_file.py understand win32file primitives for better awesomeness. v1.0c1 Version 1.0 Release Candidate 1 - Documentation for the library has switched to epydoc: http://google-api-python-client.googlecode.com/hg/docs/epy/index.html - Many improvements for media support: * Added media download support, including resumable downloads. * Better handling of streams that report their size as 0. * Update Media Upload to include io.Base and also fix some bugs. - OAuth bug fixes and improvements. * Remove OAuth 1.0 support. * Added credentials_from_code and credentials_from_clientsecrets_and_code. * Make oauth2client support Windows-friendly locking. * Fix bug in StorageByKeyName. * Fix None handling in Django fields. Reviewed in http://codereview.appspot.com/6298084/. Fixes issue #128. - Add epydoc generated docs. Reviewed in http://codereview.appspot.com/6305043/ - Move to PEP386 compliant version numbers. - New and updated samples * Ad Exchange Buyer API v1 code samples. * Automatically generate Samples wiki page from README files. * Update Google Prediction samples. * Add a Tasks sample that demonstrates Service accounts. * new analytics api samples. Reviewed here: http://codereview.appspot.com/5494058/ - Convert all inline samples to the Farm API for consistency. v1.0beta8 - Updated meda upload support. - Many fixes for batch requests. - Better handling for requests that don't require a body. - Fix issues with Google App Engine Python 2.7 runtime. - Better support for proxies. - All Storages now have a .delete() method. - Important changes which might break your code: * apiclient.anyjson has moved to oauth2client.anyjson. * Some calls, for example, taskqueue().lease() used to require a parameter named body. In this new release only methods that really need to send a body require a body parameter, and so you may get errors about an unknown 'body' parameter in your call. The solution is to remove the unneeded body={} parameter. v1.0beta7 - Support for batch requests. http://code.google.com/p/google-api-python-client/wiki/Batch - Support for media upload. http://code.google.com/p/google-api-python-client/wiki/MediaUpload - Better handling for APIs that return something other than JSON. - Major cleanup and consolidation of the samples. - Bug fixes and other enhancements: 72 Defect Appengine OAuth2Decorator: Convert redirect address to string 22 Defect Better error handling for unknown service name or version 48 Defect StorageByKeyName().get() has side effects 50 Defect Need sample client code for Admin Audit API 28 Defect better comments for app engine sample Nov 9 63 Enhancement Let OAuth2Decorator take a list of scope google-api-python-client-1.2/setup.cfg0000640017135500116100000000007312200467672020747 0ustar jcgregorioeng00000000000000[egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 google-api-python-client-1.2/PKG-INFO0000640017135500116100000000124512200467672020225 0ustar jcgregorioeng00000000000000Metadata-Version: 1.1 Name: google-api-python-client Version: 1.2 Summary: Google API Client Library for Python Home-page: http://code.google.com/p/google-api-python-client/ Author: Joe Gregorio Author-email: jcgregorio@google.com License: Apache 2.0 Description: The Google API Client for Python is a client library for accessing the Plus, Moderator, and many other Google APIs. Keywords: google api client Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Apache Software License Classifier: Operating System :: POSIX Classifier: Topic :: Internet :: WWW/HTTP google-api-python-client-1.2/apiclient/0000750017135500116100000000000012200467672021075 5ustar jcgregorioeng00000000000000google-api-python-client-1.2/apiclient/sample_tools.py0000640017135500116100000000671012173557443024162 0ustar jcgregorioeng00000000000000# Copyright (C) 2013 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for making samples. Consolidates a lot of code commonly repeated in sample applications. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' __all__ = ['init'] import argparse import httplib2 import os from apiclient import discovery from oauth2client import client from oauth2client import file from oauth2client import tools def init(argv, name, version, doc, filename, scope=None, parents=[]): """A common initialization routine for samples. Many of the sample applications do the same initialization, which has now been consolidated into this function. This function uses common idioms found in almost all the samples, i.e. for an API with name 'apiname', the credentials are stored in a file named apiname.dat, and the client_secrets.json file is stored in the same directory as the application main file. Args: argv: list of string, the command-line parameters of the application. name: string, name of the API. version: string, version of the API. doc: string, description of the application. Usually set to __doc__. file: string, filename of the application. Usually set to __file__. parents: list of argparse.ArgumentParser, additional command-line flags. scope: string, The OAuth scope used. Returns: A tuple of (service, flags), where service is the service object and flags is the parsed command-line flags. """ if scope is None: scope = 'https://www.googleapis.com/auth/' + name # Parser command-line arguments. parent_parsers = [tools.argparser] parent_parsers.extend(parents) parser = argparse.ArgumentParser( description=doc, formatter_class=argparse.RawDescriptionHelpFormatter, parents=parent_parsers) flags = parser.parse_args(argv[1:]) # Name of a file containing the OAuth 2.0 information for this # application, including client_id and client_secret, which are found # on the API Access tab on the Google APIs # Console . client_secrets = os.path.join(os.path.dirname(filename), 'client_secrets.json') # Set up a Flow object to be used if we need to authenticate. flow = client.flow_from_clientsecrets(client_secrets, scope=scope, message=tools.message_if_missing(client_secrets)) # Prepare credentials, and authorize HTTP object with them. # If the credentials don't exist or are invalid run through the native client # flow. The Storage object will ensure that if successful the good # credentials will get written back to a file. storage = file.Storage(name + '.dat') credentials = storage.get() if credentials is None or credentials.invalid: credentials = tools.run_flow(flow, storage, flags) http = credentials.authorize(http = httplib2.Http()) # Construct a service object via the discovery service. service = discovery.build(name, version, http=http) return (service, flags) google-api-python-client-1.2/apiclient/errors.py0000640017135500116100000000667412173557443023006 0ustar jcgregorioeng00000000000000#!/usr/bin/python2.4 # # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Errors for the library. All exceptions defined by the library should be defined in this file. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' from oauth2client import util from oauth2client.anyjson import simplejson class Error(Exception): """Base error for this module.""" pass class HttpError(Error): """HTTP data was invalid or unexpected.""" @util.positional(3) def __init__(self, resp, content, uri=None): self.resp = resp self.content = content self.uri = uri def _get_reason(self): """Calculate the reason for the error from the response content.""" reason = self.resp.reason try: data = simplejson.loads(self.content) reason = data['error']['message'] except (ValueError, KeyError): pass if reason is None: reason = '' return reason def __repr__(self): if self.uri: return '' % ( self.resp.status, self.uri, self._get_reason().strip()) else: return '' % (self.resp.status, self._get_reason()) __str__ = __repr__ class InvalidJsonError(Error): """The JSON returned could not be parsed.""" pass class UnknownFileType(Error): """File type unknown or unexpected.""" pass class UnknownLinkType(Error): """Link type unknown or unexpected.""" pass class UnknownApiNameOrVersion(Error): """No API with that name and version exists.""" pass class UnacceptableMimeTypeError(Error): """That is an unacceptable mimetype for this operation.""" pass class MediaUploadSizeError(Error): """Media is larger than the method can accept.""" pass class ResumableUploadError(HttpError): """Error occured during resumable upload.""" pass class InvalidChunkSizeError(Error): """The given chunksize is not valid.""" pass class InvalidNotificationError(Error): """The channel Notification is invalid.""" pass class BatchError(HttpError): """Error occured during batch operations.""" @util.positional(2) def __init__(self, reason, resp=None, content=None): self.resp = resp self.content = content self.reason = reason def __repr__(self): return '' % (self.resp.status, self.reason) __str__ = __repr__ class UnexpectedMethodError(Error): """Exception raised by RequestMockBuilder on unexpected calls.""" @util.positional(1) def __init__(self, methodId=None): """Constructor for an UnexpectedMethodError.""" super(UnexpectedMethodError, self).__init__( 'Received unexpected call %s' % methodId) class UnexpectedBodyError(Error): """Exception raised by RequestMockBuilder on unexpected bodies.""" def __init__(self, expected, provided): """Constructor for an UnexpectedMethodError.""" super(UnexpectedBodyError, self).__init__( 'Expected: [%s] - Provided: [%s]' % (expected, provided)) google-api-python-client-1.2/apiclient/model.py0000640017135500116100000002667412200460220022545 0ustar jcgregorioeng00000000000000#!/usr/bin/python2.4 # # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Model objects for requests and responses. Each API may support one or more serializations, such as JSON, Atom, etc. The model classes are responsible for converting between the wire format and the Python object representation. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import logging import urllib from apiclient import __version__ from errors import HttpError from oauth2client.anyjson import simplejson dump_request_response = False def _abstract(): raise NotImplementedError('You need to override this function') class Model(object): """Model base class. All Model classes should implement this interface. The Model serializes and de-serializes between a wire format such as JSON and a Python object representation. """ def request(self, headers, path_params, query_params, body_value): """Updates outgoing requests with a serialized body. Args: headers: dict, request headers path_params: dict, parameters that appear in the request path query_params: dict, parameters that appear in the query body_value: object, the request body as a Python object, which must be serializable. Returns: A tuple of (headers, path_params, query, body) headers: dict, request headers path_params: dict, parameters that appear in the request path query: string, query part of the request URI body: string, the body serialized in the desired wire format. """ _abstract() def response(self, resp, content): """Convert the response wire format into a Python object. Args: resp: httplib2.Response, the HTTP response headers and status content: string, the body of the HTTP response Returns: The body de-serialized as a Python object. Raises: apiclient.errors.HttpError if a non 2xx response is received. """ _abstract() class BaseModel(Model): """Base model class. Subclasses should provide implementations for the "serialize" and "deserialize" methods, as well as values for the following class attributes. Attributes: accept: The value to use for the HTTP Accept header. content_type: The value to use for the HTTP Content-type header. no_content_response: The value to return when deserializing a 204 "No Content" response. alt_param: The value to supply as the "alt" query parameter for requests. """ accept = None content_type = None no_content_response = None alt_param = None def _log_request(self, headers, path_params, query, body): """Logs debugging information about the request if requested.""" if dump_request_response: logging.info('--request-start--') logging.info('-headers-start-') for h, v in headers.iteritems(): logging.info('%s: %s', h, v) logging.info('-headers-end-') logging.info('-path-parameters-start-') for h, v in path_params.iteritems(): logging.info('%s: %s', h, v) logging.info('-path-parameters-end-') logging.info('body: %s', body) logging.info('query: %s', query) logging.info('--request-end--') def request(self, headers, path_params, query_params, body_value): """Updates outgoing requests with a serialized body. Args: headers: dict, request headers path_params: dict, parameters that appear in the request path query_params: dict, parameters that appear in the query body_value: object, the request body as a Python object, which must be serializable by simplejson. Returns: A tuple of (headers, path_params, query, body) headers: dict, request headers path_params: dict, parameters that appear in the request path query: string, query part of the request URI body: string, the body serialized as JSON """ query = self._build_query(query_params) headers['accept'] = self.accept headers['accept-encoding'] = 'gzip, deflate' if 'user-agent' in headers: headers['user-agent'] += ' ' else: headers['user-agent'] = '' headers['user-agent'] += 'google-api-python-client/%s (gzip)' % __version__ if body_value is not None: headers['content-type'] = self.content_type body_value = self.serialize(body_value) self._log_request(headers, path_params, query, body_value) return (headers, path_params, query, body_value) def _build_query(self, params): """Builds a query string. Args: params: dict, the query parameters Returns: The query parameters properly encoded into an HTTP URI query string. """ if self.alt_param is not None: params.update({'alt': self.alt_param}) astuples = [] for key, value in params.iteritems(): if type(value) == type([]): for x in value: x = x.encode('utf-8') astuples.append((key, x)) else: if getattr(value, 'encode', False) and callable(value.encode): value = value.encode('utf-8') astuples.append((key, value)) return '?' + urllib.urlencode(astuples) def _log_response(self, resp, content): """Logs debugging information about the response if requested.""" if dump_request_response: logging.info('--response-start--') for h, v in resp.iteritems(): logging.info('%s: %s', h, v) if content: logging.info(content) logging.info('--response-end--') def response(self, resp, content): """Convert the response wire format into a Python object. Args: resp: httplib2.Response, the HTTP response headers and status content: string, the body of the HTTP response Returns: The body de-serialized as a Python object. Raises: apiclient.errors.HttpError if a non 2xx response is received. """ self._log_response(resp, content) # Error handling is TBD, for example, do we retry # for some operation/error combinations? if resp.status < 300: if resp.status == 204: # A 204: No Content response should be treated differently # to all the other success states return self.no_content_response return self.deserialize(content) else: logging.debug('Content from bad request was: %s' % content) raise HttpError(resp, content) def serialize(self, body_value): """Perform the actual Python object serialization. Args: body_value: object, the request body as a Python object. Returns: string, the body in serialized form. """ _abstract() def deserialize(self, content): """Perform the actual deserialization from response string to Python object. Args: content: string, the body of the HTTP response Returns: The body de-serialized as a Python object. """ _abstract() class JsonModel(BaseModel): """Model class for JSON. Serializes and de-serializes between JSON and the Python object representation of HTTP request and response bodies. """ accept = 'application/json' content_type = 'application/json' alt_param = 'json' def __init__(self, data_wrapper=False): """Construct a JsonModel. Args: data_wrapper: boolean, wrap requests and responses in a data wrapper """ self._data_wrapper = data_wrapper def serialize(self, body_value): if (isinstance(body_value, dict) and 'data' not in body_value and self._data_wrapper): body_value = {'data': body_value} return simplejson.dumps(body_value) def deserialize(self, content): content = content.decode('utf-8') body = simplejson.loads(content) if self._data_wrapper and isinstance(body, dict) and 'data' in body: body = body['data'] return body @property def no_content_response(self): return {} class RawModel(JsonModel): """Model class for requests that don't return JSON. Serializes and de-serializes between JSON and the Python object representation of HTTP request, and returns the raw bytes of the response body. """ accept = '*/*' content_type = 'application/json' alt_param = None def deserialize(self, content): return content @property def no_content_response(self): return '' class MediaModel(JsonModel): """Model class for requests that return Media. Serializes and de-serializes between JSON and the Python object representation of HTTP request, and returns the raw bytes of the response body. """ accept = '*/*' content_type = 'application/json' alt_param = 'media' def deserialize(self, content): return content @property def no_content_response(self): return '' class ProtocolBufferModel(BaseModel): """Model class for protocol buffers. Serializes and de-serializes the binary protocol buffer sent in the HTTP request and response bodies. """ accept = 'application/x-protobuf' content_type = 'application/x-protobuf' alt_param = 'proto' def __init__(self, protocol_buffer): """Constructs a ProtocolBufferModel. The serialzed protocol buffer returned in an HTTP response will be de-serialized using the given protocol buffer class. Args: protocol_buffer: The protocol buffer class used to de-serialize a response from the API. """ self._protocol_buffer = protocol_buffer def serialize(self, body_value): return body_value.SerializeToString() def deserialize(self, content): return self._protocol_buffer.FromString(content) @property def no_content_response(self): return self._protocol_buffer() def makepatch(original, modified): """Create a patch object. Some methods support PATCH, an efficient way to send updates to a resource. This method allows the easy construction of patch bodies by looking at the differences between a resource before and after it was modified. Args: original: object, the original deserialized resource modified: object, the modified deserialized resource Returns: An object that contains only the changes from original to modified, in a form suitable to pass to a PATCH method. Example usage: item = service.activities().get(postid=postid, userid=userid).execute() original = copy.deepcopy(item) item['object']['content'] = 'This is updated.' service.activities.patch(postid=postid, userid=userid, body=makepatch(original, item)).execute() """ patch = {} for key, original_value in original.iteritems(): modified_value = modified.get(key, None) if modified_value is None: # Use None to signal that the element is deleted patch[key] = None elif original_value != modified_value: if type(original_value) == type({}): # Recursively descend objects patch[key] = makepatch(original_value, modified_value) else: # In the case of simple types or arrays we just replace patch[key] = modified_value else: # Don't add anything to patch if there's no change pass for key in modified: if key not in original: patch[key] = modified[key] return patch google-api-python-client-1.2/apiclient/mimeparse.py0000640017135500116100000001452612173557443023447 0ustar jcgregorioeng00000000000000# Copyright (C) 2007 Joe Gregorio # # Licensed under the MIT License """MIME-Type Parser This module provides basic functions for handling mime-types. It can handle matching mime-types against a list of media-ranges. See section 14.1 of the HTTP specification [RFC 2616] for a complete explanation. http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1 Contents: - parse_mime_type(): Parses a mime-type into its component parts. - parse_media_range(): Media-ranges are mime-types with wild-cards and a 'q' quality parameter. - quality(): Determines the quality ('q') of a mime-type when compared against a list of media-ranges. - quality_parsed(): Just like quality() except the second parameter must be pre-parsed. - best_match(): Choose the mime-type with the highest quality ('q') from a list of candidates. """ __version__ = '0.1.3' __author__ = 'Joe Gregorio' __email__ = 'joe@bitworking.org' __license__ = 'MIT License' __credits__ = '' def parse_mime_type(mime_type): """Parses a mime-type into its component parts. Carves up a mime-type and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/xhtml;q=0.5' would get parsed into: ('application', 'xhtml', {'q', '0.5'}) """ parts = mime_type.split(';') params = dict([tuple([s.strip() for s in param.split('=', 1)])\ for param in parts[1:] ]) full_type = parts[0].strip() # Java URLConnection class sends an Accept header that includes a # single '*'. Turn it into a legal wildcard. if full_type == '*': full_type = '*/*' (type, subtype) = full_type.split('/') return (type.strip(), subtype.strip(), params) def parse_media_range(range): """Parse a media-range into its component parts. Carves up a media range and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/*;q=0.5' would get parsed into: ('application', '*', {'q', '0.5'}) In addition this function also guarantees that there is a value for 'q' in the params dictionary, filling it in with a proper default if necessary. """ (type, subtype, params) = parse_mime_type(range) if not params.has_key('q') or not params['q'] or \ not float(params['q']) or float(params['q']) > 1\ or float(params['q']) < 0: params['q'] = '1' return (type, subtype, params) def fitness_and_quality_parsed(mime_type, parsed_ranges): """Find the best match for a mime-type amongst parsed media-ranges. Find the best match for a given mime-type against a list of media_ranges that have already been parsed by parse_media_range(). Returns a tuple of the fitness value and the value of the 'q' quality parameter of the best match, or (-1, 0) if no match was found. Just as for quality_parsed(), 'parsed_ranges' must be a list of parsed media ranges. """ best_fitness = -1 best_fit_q = 0 (target_type, target_subtype, target_params) =\ parse_media_range(mime_type) for (type, subtype, params) in parsed_ranges: type_match = (type == target_type or\ type == '*' or\ target_type == '*') subtype_match = (subtype == target_subtype or\ subtype == '*' or\ target_subtype == '*') if type_match and subtype_match: param_matches = reduce(lambda x, y: x + y, [1 for (key, value) in \ target_params.iteritems() if key != 'q' and \ params.has_key(key) and value == params[key]], 0) fitness = (type == target_type) and 100 or 0 fitness += (subtype == target_subtype) and 10 or 0 fitness += param_matches if fitness > best_fitness: best_fitness = fitness best_fit_q = params['q'] return best_fitness, float(best_fit_q) def quality_parsed(mime_type, parsed_ranges): """Find the best match for a mime-type amongst parsed media-ranges. Find the best match for a given mime-type against a list of media_ranges that have already been parsed by parse_media_range(). Returns the 'q' quality parameter of the best match, 0 if no match was found. This function bahaves the same as quality() except that 'parsed_ranges' must be a list of parsed media ranges. """ return fitness_and_quality_parsed(mime_type, parsed_ranges)[1] def quality(mime_type, ranges): """Return the quality ('q') of a mime-type against a list of media-ranges. Returns the quality 'q' of a mime-type when compared against the media-ranges in ranges. For example: >>> quality('text/html','text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5') 0.7 """ parsed_ranges = [parse_media_range(r) for r in ranges.split(',')] return quality_parsed(mime_type, parsed_ranges) def best_match(supported, header): """Return mime-type with the highest quality ('q') from list of candidates. Takes a list of supported mime-types and finds the best match for all the media-ranges listed in header. The value of header must be a string that conforms to the format of the HTTP Accept: header. The value of 'supported' is a list of mime-types. The list of supported mime-types should be sorted in order of increasing desirability, in case of a situation where there is a tie. >>> best_match(['application/xbel+xml', 'text/xml'], 'text/*;q=0.5,*/*; q=0.1') 'text/xml' """ split_header = _filter_blank(header.split(',')) parsed_header = [parse_media_range(r) for r in split_header] weighted_matches = [] pos = 0 for mime_type in supported: weighted_matches.append((fitness_and_quality_parsed(mime_type, parsed_header), pos, mime_type)) pos += 1 weighted_matches.sort() return weighted_matches[-1][0][1] and weighted_matches[-1][2] or '' def _filter_blank(i): for s in i: if s.strip(): yield s google-api-python-client-1.2/apiclient/discovery.py0000640017135500116100000010600712173557443023470 0ustar jcgregorioeng00000000000000# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Client for discovery based APIs. A client library for Google's discovery based APIs. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' __all__ = [ 'build', 'build_from_document', 'fix_method_name', 'key2param', ] # Standard library imports import copy from email.mime.multipart import MIMEMultipart from email.mime.nonmultipart import MIMENonMultipart import keyword import logging import mimetypes import os import re import urllib import urlparse try: from urlparse import parse_qsl except ImportError: from cgi import parse_qsl # Third-party imports import httplib2 import mimeparse import uritemplate # Local imports from apiclient.errors import HttpError from apiclient.errors import InvalidJsonError from apiclient.errors import MediaUploadSizeError from apiclient.errors import UnacceptableMimeTypeError from apiclient.errors import UnknownApiNameOrVersion from apiclient.errors import UnknownFileType from apiclient.http import HttpRequest from apiclient.http import MediaFileUpload from apiclient.http import MediaUpload from apiclient.model import JsonModel from apiclient.model import MediaModel from apiclient.model import RawModel from apiclient.schema import Schemas from oauth2client.anyjson import simplejson from oauth2client.util import _add_query_parameter from oauth2client.util import positional # The client library requires a version of httplib2 that supports RETRIES. httplib2.RETRIES = 1 logger = logging.getLogger(__name__) URITEMPLATE = re.compile('{[^}]*}') VARNAME = re.compile('[a-zA-Z0-9_-]+') DISCOVERY_URI = ('https://www.googleapis.com/discovery/v1/apis/' '{api}/{apiVersion}/rest') DEFAULT_METHOD_DOC = 'A description of how to use this function' HTTP_PAYLOAD_METHODS = frozenset(['PUT', 'POST', 'PATCH']) _MEDIA_SIZE_BIT_SHIFTS = {'KB': 10, 'MB': 20, 'GB': 30, 'TB': 40} BODY_PARAMETER_DEFAULT_VALUE = { 'description': 'The request body.', 'type': 'object', 'required': True, } MEDIA_BODY_PARAMETER_DEFAULT_VALUE = { 'description': ('The filename of the media request body, or an instance ' 'of a MediaUpload object.'), 'type': 'string', 'required': False, } # Parameters accepted by the stack, but not visible via discovery. # TODO(dhermes): Remove 'userip' in 'v2'. STACK_QUERY_PARAMETERS = frozenset(['trace', 'pp', 'userip', 'strict']) STACK_QUERY_PARAMETER_DEFAULT_VALUE = {'type': 'string', 'location': 'query'} # Library-specific reserved words beyond Python keywords. RESERVED_WORDS = frozenset(['body']) def fix_method_name(name): """Fix method names to avoid reserved word conflicts. Args: name: string, method name. Returns: The name with a '_' prefixed if the name is a reserved word. """ if keyword.iskeyword(name) or name in RESERVED_WORDS: return name + '_' else: return name def key2param(key): """Converts key names into parameter names. For example, converting "max-results" -> "max_results" Args: key: string, the method key name. Returns: A safe method name based on the key name. """ result = [] key = list(key) if not key[0].isalpha(): result.append('x') for c in key: if c.isalnum(): result.append(c) else: result.append('_') return ''.join(result) @positional(2) def build(serviceName, version, http=None, discoveryServiceUrl=DISCOVERY_URI, developerKey=None, model=None, requestBuilder=HttpRequest): """Construct a Resource for interacting with an API. Construct a Resource object for interacting with an API. The serviceName and version are the names from the Discovery service. Args: serviceName: string, name of the service. version: string, the version of the service. http: httplib2.Http, An instance of httplib2.Http or something that acts like it that HTTP requests will be made through. discoveryServiceUrl: string, a URI Template that points to the location of the discovery service. It should have two parameters {api} and {apiVersion} that when filled in produce an absolute URI to the discovery document for that service. developerKey: string, key obtained from https://code.google.com/apis/console. model: apiclient.Model, converts to and from the wire format. requestBuilder: apiclient.http.HttpRequest, encapsulator for an HTTP request. Returns: A Resource object with methods for interacting with the service. """ params = { 'api': serviceName, 'apiVersion': version } if http is None: http = httplib2.Http() requested_url = uritemplate.expand(discoveryServiceUrl, params) # REMOTE_ADDR is defined by the CGI spec [RFC3875] as the environment # variable that contains the network address of the client sending the # request. If it exists then add that to the request for the discovery # document to avoid exceeding the quota on discovery requests. if 'REMOTE_ADDR' in os.environ: requested_url = _add_query_parameter(requested_url, 'userIp', os.environ['REMOTE_ADDR']) logger.info('URL being requested: %s' % requested_url) resp, content = http.request(requested_url) if resp.status == 404: raise UnknownApiNameOrVersion("name: %s version: %s" % (serviceName, version)) if resp.status >= 400: raise HttpError(resp, content, uri=requested_url) try: service = simplejson.loads(content) except ValueError, e: logger.error('Failed to parse as JSON: ' + content) raise InvalidJsonError() return build_from_document(content, base=discoveryServiceUrl, http=http, developerKey=developerKey, model=model, requestBuilder=requestBuilder) @positional(1) def build_from_document( service, base=None, future=None, http=None, developerKey=None, model=None, requestBuilder=HttpRequest): """Create a Resource for interacting with an API. Same as `build()`, but constructs the Resource object from a discovery document that is it given, as opposed to retrieving one over HTTP. Args: service: string or object, the JSON discovery document describing the API. The value passed in may either be the JSON string or the deserialized JSON. base: string, base URI for all HTTP requests, usually the discovery URI. This parameter is no longer used as rootUrl and servicePath are included within the discovery document. (deprecated) future: string, discovery document with future capabilities (deprecated). http: httplib2.Http, An instance of httplib2.Http or something that acts like it that HTTP requests will be made through. developerKey: string, Key for controlling API usage, generated from the API Console. model: Model class instance that serializes and de-serializes requests and responses. requestBuilder: Takes an http request and packages it up to be executed. Returns: A Resource object with methods for interacting with the service. """ # future is no longer used. future = {} if isinstance(service, basestring): service = simplejson.loads(service) base = urlparse.urljoin(service['rootUrl'], service['servicePath']) schema = Schemas(service) if model is None: features = service.get('features', []) model = JsonModel('dataWrapper' in features) return Resource(http=http, baseUrl=base, model=model, developerKey=developerKey, requestBuilder=requestBuilder, resourceDesc=service, rootDesc=service, schema=schema) def _cast(value, schema_type): """Convert value to a string based on JSON Schema type. See http://tools.ietf.org/html/draft-zyp-json-schema-03 for more details on JSON Schema. Args: value: any, the value to convert schema_type: string, the type that value should be interpreted as Returns: A string representation of 'value' based on the schema_type. """ if schema_type == 'string': if type(value) == type('') or type(value) == type(u''): return value else: return str(value) elif schema_type == 'integer': return str(int(value)) elif schema_type == 'number': return str(float(value)) elif schema_type == 'boolean': return str(bool(value)).lower() else: if type(value) == type('') or type(value) == type(u''): return value else: return str(value) def _media_size_to_long(maxSize): """Convert a string media size, such as 10GB or 3TB into an integer. Args: maxSize: string, size as a string, such as 2MB or 7GB. Returns: The size as an integer value. """ if len(maxSize) < 2: return 0L units = maxSize[-2:].upper() bit_shift = _MEDIA_SIZE_BIT_SHIFTS.get(units) if bit_shift is not None: return long(maxSize[:-2]) << bit_shift else: return long(maxSize) def _media_path_url_from_info(root_desc, path_url): """Creates an absolute media path URL. Constructed using the API root URI and service path from the discovery document and the relative path for the API method. Args: root_desc: Dictionary; the entire original deserialized discovery document. path_url: String; the relative URL for the API method. Relative to the API root, which is specified in the discovery document. Returns: String; the absolute URI for media upload for the API method. """ return '%(root)supload/%(service_path)s%(path)s' % { 'root': root_desc['rootUrl'], 'service_path': root_desc['servicePath'], 'path': path_url, } def _fix_up_parameters(method_desc, root_desc, http_method): """Updates parameters of an API method with values specific to this library. Specifically, adds whatever global parameters are specified by the API to the parameters for the individual method. Also adds parameters which don't appear in the discovery document, but are available to all discovery based APIs (these are listed in STACK_QUERY_PARAMETERS). SIDE EFFECTS: This updates the parameters dictionary object in the method description. Args: method_desc: Dictionary with metadata describing an API method. Value comes from the dictionary of methods stored in the 'methods' key in the deserialized discovery document. root_desc: Dictionary; the entire original deserialized discovery document. http_method: String; the HTTP method used to call the API method described in method_desc. Returns: The updated Dictionary stored in the 'parameters' key of the method description dictionary. """ parameters = method_desc.setdefault('parameters', {}) # Add in the parameters common to all methods. for name, description in root_desc.get('parameters', {}).iteritems(): parameters[name] = description # Add in undocumented query parameters. for name in STACK_QUERY_PARAMETERS: parameters[name] = STACK_QUERY_PARAMETER_DEFAULT_VALUE.copy() # Add 'body' (our own reserved word) to parameters if the method supports # a request payload. if http_method in HTTP_PAYLOAD_METHODS and 'request' in method_desc: body = BODY_PARAMETER_DEFAULT_VALUE.copy() body.update(method_desc['request']) parameters['body'] = body return parameters def _fix_up_media_upload(method_desc, root_desc, path_url, parameters): """Updates parameters of API by adding 'media_body' if supported by method. SIDE EFFECTS: If the method supports media upload and has a required body, sets body to be optional (required=False) instead. Also, if there is a 'mediaUpload' in the method description, adds 'media_upload' key to parameters. Args: method_desc: Dictionary with metadata describing an API method. Value comes from the dictionary of methods stored in the 'methods' key in the deserialized discovery document. root_desc: Dictionary; the entire original deserialized discovery document. path_url: String; the relative URL for the API method. Relative to the API root, which is specified in the discovery document. parameters: A dictionary describing method parameters for method described in method_desc. Returns: Triple (accept, max_size, media_path_url) where: - accept is a list of strings representing what content types are accepted for media upload. Defaults to empty list if not in the discovery document. - max_size is a long representing the max size in bytes allowed for a media upload. Defaults to 0L if not in the discovery document. - media_path_url is a String; the absolute URI for media upload for the API method. Constructed using the API root URI and service path from the discovery document and the relative path for the API method. If media upload is not supported, this is None. """ media_upload = method_desc.get('mediaUpload', {}) accept = media_upload.get('accept', []) max_size = _media_size_to_long(media_upload.get('maxSize', '')) media_path_url = None if media_upload: media_path_url = _media_path_url_from_info(root_desc, path_url) parameters['media_body'] = MEDIA_BODY_PARAMETER_DEFAULT_VALUE.copy() if 'body' in parameters: parameters['body']['required'] = False return accept, max_size, media_path_url def _fix_up_method_description(method_desc, root_desc): """Updates a method description in a discovery document. SIDE EFFECTS: Changes the parameters dictionary in the method description with extra parameters which are used locally. Args: method_desc: Dictionary with metadata describing an API method. Value comes from the dictionary of methods stored in the 'methods' key in the deserialized discovery document. root_desc: Dictionary; the entire original deserialized discovery document. Returns: Tuple (path_url, http_method, method_id, accept, max_size, media_path_url) where: - path_url is a String; the relative URL for the API method. Relative to the API root, which is specified in the discovery document. - http_method is a String; the HTTP method used to call the API method described in the method description. - method_id is a String; the name of the RPC method associated with the API method, and is in the method description in the 'id' key. - accept is a list of strings representing what content types are accepted for media upload. Defaults to empty list if not in the discovery document. - max_size is a long representing the max size in bytes allowed for a media upload. Defaults to 0L if not in the discovery document. - media_path_url is a String; the absolute URI for media upload for the API method. Constructed using the API root URI and service path from the discovery document and the relative path for the API method. If media upload is not supported, this is None. """ path_url = method_desc['path'] http_method = method_desc['httpMethod'] method_id = method_desc['id'] parameters = _fix_up_parameters(method_desc, root_desc, http_method) # Order is important. `_fix_up_media_upload` needs `method_desc` to have a # 'parameters' key and needs to know if there is a 'body' parameter because it # also sets a 'media_body' parameter. accept, max_size, media_path_url = _fix_up_media_upload( method_desc, root_desc, path_url, parameters) return path_url, http_method, method_id, accept, max_size, media_path_url # TODO(dhermes): Convert this class to ResourceMethod and make it callable class ResourceMethodParameters(object): """Represents the parameters associated with a method. Attributes: argmap: Map from method parameter name (string) to query parameter name (string). required_params: List of required parameters (represented by parameter name as string). repeated_params: List of repeated parameters (represented by parameter name as string). pattern_params: Map from method parameter name (string) to regular expression (as a string). If the pattern is set for a parameter, the value for that parameter must match the regular expression. query_params: List of parameters (represented by parameter name as string) that will be used in the query string. path_params: Set of parameters (represented by parameter name as string) that will be used in the base URL path. param_types: Map from method parameter name (string) to parameter type. Type can be any valid JSON schema type; valid values are 'any', 'array', 'boolean', 'integer', 'number', 'object', or 'string'. Reference: http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.1 enum_params: Map from method parameter name (string) to list of strings, where each list of strings is the list of acceptable enum values. """ def __init__(self, method_desc): """Constructor for ResourceMethodParameters. Sets default values and defers to set_parameters to populate. Args: method_desc: Dictionary with metadata describing an API method. Value comes from the dictionary of methods stored in the 'methods' key in the deserialized discovery document. """ self.argmap = {} self.required_params = [] self.repeated_params = [] self.pattern_params = {} self.query_params = [] # TODO(dhermes): Change path_params to a list if the extra URITEMPLATE # parsing is gotten rid of. self.path_params = set() self.param_types = {} self.enum_params = {} self.set_parameters(method_desc) def set_parameters(self, method_desc): """Populates maps and lists based on method description. Iterates through each parameter for the method and parses the values from the parameter dictionary. Args: method_desc: Dictionary with metadata describing an API method. Value comes from the dictionary of methods stored in the 'methods' key in the deserialized discovery document. """ for arg, desc in method_desc.get('parameters', {}).iteritems(): param = key2param(arg) self.argmap[param] = arg if desc.get('pattern'): self.pattern_params[param] = desc['pattern'] if desc.get('enum'): self.enum_params[param] = desc['enum'] if desc.get('required'): self.required_params.append(param) if desc.get('repeated'): self.repeated_params.append(param) if desc.get('location') == 'query': self.query_params.append(param) if desc.get('location') == 'path': self.path_params.add(param) self.param_types[param] = desc.get('type', 'string') # TODO(dhermes): Determine if this is still necessary. Discovery based APIs # should have all path parameters already marked with # 'location: path'. for match in URITEMPLATE.finditer(method_desc['path']): for namematch in VARNAME.finditer(match.group(0)): name = key2param(namematch.group(0)) self.path_params.add(name) if name in self.query_params: self.query_params.remove(name) def createMethod(methodName, methodDesc, rootDesc, schema): """Creates a method for attaching to a Resource. Args: methodName: string, name of the method to use. methodDesc: object, fragment of deserialized discovery document that describes the method. rootDesc: object, the entire deserialized discovery document. schema: object, mapping of schema names to schema descriptions. """ methodName = fix_method_name(methodName) (pathUrl, httpMethod, methodId, accept, maxSize, mediaPathUrl) = _fix_up_method_description(methodDesc, rootDesc) parameters = ResourceMethodParameters(methodDesc) def method(self, **kwargs): # Don't bother with doc string, it will be over-written by createMethod. for name in kwargs.iterkeys(): if name not in parameters.argmap: raise TypeError('Got an unexpected keyword argument "%s"' % name) # Remove args that have a value of None. keys = kwargs.keys() for name in keys: if kwargs[name] is None: del kwargs[name] for name in parameters.required_params: if name not in kwargs: raise TypeError('Missing required parameter "%s"' % name) for name, regex in parameters.pattern_params.iteritems(): if name in kwargs: if isinstance(kwargs[name], basestring): pvalues = [kwargs[name]] else: pvalues = kwargs[name] for pvalue in pvalues: if re.match(regex, pvalue) is None: raise TypeError( 'Parameter "%s" value "%s" does not match the pattern "%s"' % (name, pvalue, regex)) for name, enums in parameters.enum_params.iteritems(): if name in kwargs: # We need to handle the case of a repeated enum # name differently, since we want to handle both # arg='value' and arg=['value1', 'value2'] if (name in parameters.repeated_params and not isinstance(kwargs[name], basestring)): values = kwargs[name] else: values = [kwargs[name]] for value in values: if value not in enums: raise TypeError( 'Parameter "%s" value "%s" is not an allowed value in "%s"' % (name, value, str(enums))) actual_query_params = {} actual_path_params = {} for key, value in kwargs.iteritems(): to_type = parameters.param_types.get(key, 'string') # For repeated parameters we cast each member of the list. if key in parameters.repeated_params and type(value) == type([]): cast_value = [_cast(x, to_type) for x in value] else: cast_value = _cast(value, to_type) if key in parameters.query_params: actual_query_params[parameters.argmap[key]] = cast_value if key in parameters.path_params: actual_path_params[parameters.argmap[key]] = cast_value body_value = kwargs.get('body', None) media_filename = kwargs.get('media_body', None) if self._developerKey: actual_query_params['key'] = self._developerKey model = self._model if methodName.endswith('_media'): model = MediaModel() elif 'response' not in methodDesc: model = RawModel() headers = {} headers, params, query, body = model.request(headers, actual_path_params, actual_query_params, body_value) expanded_url = uritemplate.expand(pathUrl, params) url = urlparse.urljoin(self._baseUrl, expanded_url + query) resumable = None multipart_boundary = '' if media_filename: # Ensure we end up with a valid MediaUpload object. if isinstance(media_filename, basestring): (media_mime_type, encoding) = mimetypes.guess_type(media_filename) if media_mime_type is None: raise UnknownFileType(media_filename) if not mimeparse.best_match([media_mime_type], ','.join(accept)): raise UnacceptableMimeTypeError(media_mime_type) media_upload = MediaFileUpload(media_filename, mimetype=media_mime_type) elif isinstance(media_filename, MediaUpload): media_upload = media_filename else: raise TypeError('media_filename must be str or MediaUpload.') # Check the maxSize if maxSize > 0 and media_upload.size() > maxSize: raise MediaUploadSizeError("Media larger than: %s" % maxSize) # Use the media path uri for media uploads expanded_url = uritemplate.expand(mediaPathUrl, params) url = urlparse.urljoin(self._baseUrl, expanded_url + query) if media_upload.resumable(): url = _add_query_parameter(url, 'uploadType', 'resumable') if media_upload.resumable(): # This is all we need to do for resumable, if the body exists it gets # sent in the first request, otherwise an empty body is sent. resumable = media_upload else: # A non-resumable upload if body is None: # This is a simple media upload headers['content-type'] = media_upload.mimetype() body = media_upload.getbytes(0, media_upload.size()) url = _add_query_parameter(url, 'uploadType', 'media') else: # This is a multipart/related upload. msgRoot = MIMEMultipart('related') # msgRoot should not write out it's own headers setattr(msgRoot, '_write_headers', lambda self: None) # attach the body as one part msg = MIMENonMultipart(*headers['content-type'].split('/')) msg.set_payload(body) msgRoot.attach(msg) # attach the media as the second part msg = MIMENonMultipart(*media_upload.mimetype().split('/')) msg['Content-Transfer-Encoding'] = 'binary' payload = media_upload.getbytes(0, media_upload.size()) msg.set_payload(payload) msgRoot.attach(msg) body = msgRoot.as_string() multipart_boundary = msgRoot.get_boundary() headers['content-type'] = ('multipart/related; ' 'boundary="%s"') % multipart_boundary url = _add_query_parameter(url, 'uploadType', 'multipart') logger.info('URL being requested: %s' % url) return self._requestBuilder(self._http, model.response, url, method=httpMethod, body=body, headers=headers, methodId=methodId, resumable=resumable) docs = [methodDesc.get('description', DEFAULT_METHOD_DOC), '\n\n'] if len(parameters.argmap) > 0: docs.append('Args:\n') # Skip undocumented params and params common to all methods. skip_parameters = rootDesc.get('parameters', {}).keys() skip_parameters.extend(STACK_QUERY_PARAMETERS) all_args = parameters.argmap.keys() args_ordered = [key2param(s) for s in methodDesc.get('parameterOrder', [])] # Move body to the front of the line. if 'body' in all_args: args_ordered.append('body') for name in all_args: if name not in args_ordered: args_ordered.append(name) for arg in args_ordered: if arg in skip_parameters: continue repeated = '' if arg in parameters.repeated_params: repeated = ' (repeated)' required = '' if arg in parameters.required_params: required = ' (required)' paramdesc = methodDesc['parameters'][parameters.argmap[arg]] paramdoc = paramdesc.get('description', 'A parameter') if '$ref' in paramdesc: docs.append( (' %s: object, %s%s%s\n The object takes the' ' form of:\n\n%s\n\n') % (arg, paramdoc, required, repeated, schema.prettyPrintByName(paramdesc['$ref']))) else: paramtype = paramdesc.get('type', 'string') docs.append(' %s: %s, %s%s%s\n' % (arg, paramtype, paramdoc, required, repeated)) enum = paramdesc.get('enum', []) enumDesc = paramdesc.get('enumDescriptions', []) if enum and enumDesc: docs.append(' Allowed values\n') for (name, desc) in zip(enum, enumDesc): docs.append(' %s - %s\n' % (name, desc)) if 'response' in methodDesc: if methodName.endswith('_media'): docs.append('\nReturns:\n The media object as a string.\n\n ') else: docs.append('\nReturns:\n An object of the form:\n\n ') docs.append(schema.prettyPrintSchema(methodDesc['response'])) setattr(method, '__doc__', ''.join(docs)) return (methodName, method) def createNextMethod(methodName): """Creates any _next methods for attaching to a Resource. The _next methods allow for easy iteration through list() responses. Args: methodName: string, name of the method to use. """ methodName = fix_method_name(methodName) def methodNext(self, previous_request, previous_response): """Retrieves the next page of results. Args: previous_request: The request for the previous page. (required) previous_response: The response from the request for the previous page. (required) Returns: A request object that you can call 'execute()' on to request the next page. Returns None if there are no more items in the collection. """ # Retrieve nextPageToken from previous_response # Use as pageToken in previous_request to create new request. if 'nextPageToken' not in previous_response: return None request = copy.copy(previous_request) pageToken = previous_response['nextPageToken'] parsed = list(urlparse.urlparse(request.uri)) q = parse_qsl(parsed[4]) # Find and remove old 'pageToken' value from URI newq = [(key, value) for (key, value) in q if key != 'pageToken'] newq.append(('pageToken', pageToken)) parsed[4] = urllib.urlencode(newq) uri = urlparse.urlunparse(parsed) request.uri = uri logger.info('URL being requested: %s' % uri) return request return (methodName, methodNext) class Resource(object): """A class for interacting with a resource.""" def __init__(self, http, baseUrl, model, requestBuilder, developerKey, resourceDesc, rootDesc, schema): """Build a Resource from the API description. Args: http: httplib2.Http, Object to make http requests with. baseUrl: string, base URL for the API. All requests are relative to this URI. model: apiclient.Model, converts to and from the wire format. requestBuilder: class or callable that instantiates an apiclient.HttpRequest object. developerKey: string, key obtained from https://code.google.com/apis/console resourceDesc: object, section of deserialized discovery document that describes a resource. Note that the top level discovery document is considered a resource. rootDesc: object, the entire deserialized discovery document. schema: object, mapping of schema names to schema descriptions. """ self._dynamic_attrs = [] self._http = http self._baseUrl = baseUrl self._model = model self._developerKey = developerKey self._requestBuilder = requestBuilder self._resourceDesc = resourceDesc self._rootDesc = rootDesc self._schema = schema self._set_service_methods() def _set_dynamic_attr(self, attr_name, value): """Sets an instance attribute and tracks it in a list of dynamic attributes. Args: attr_name: string; The name of the attribute to be set value: The value being set on the object and tracked in the dynamic cache. """ self._dynamic_attrs.append(attr_name) self.__dict__[attr_name] = value def __getstate__(self): """Trim the state down to something that can be pickled. Uses the fact that the instance variable _dynamic_attrs holds attrs that will be wiped and restored on pickle serialization. """ state_dict = copy.copy(self.__dict__) for dynamic_attr in self._dynamic_attrs: del state_dict[dynamic_attr] del state_dict['_dynamic_attrs'] return state_dict def __setstate__(self, state): """Reconstitute the state of the object from being pickled. Uses the fact that the instance variable _dynamic_attrs holds attrs that will be wiped and restored on pickle serialization. """ self.__dict__.update(state) self._dynamic_attrs = [] self._set_service_methods() def _set_service_methods(self): self._add_basic_methods(self._resourceDesc, self._rootDesc, self._schema) self._add_nested_resources(self._resourceDesc, self._rootDesc, self._schema) self._add_next_methods(self._resourceDesc, self._schema) def _add_basic_methods(self, resourceDesc, rootDesc, schema): # Add basic methods to Resource if 'methods' in resourceDesc: for methodName, methodDesc in resourceDesc['methods'].iteritems(): fixedMethodName, method = createMethod( methodName, methodDesc, rootDesc, schema) self._set_dynamic_attr(fixedMethodName, method.__get__(self, self.__class__)) # Add in _media methods. The functionality of the attached method will # change when it sees that the method name ends in _media. if methodDesc.get('supportsMediaDownload', False): fixedMethodName, method = createMethod( methodName + '_media', methodDesc, rootDesc, schema) self._set_dynamic_attr(fixedMethodName, method.__get__(self, self.__class__)) def _add_nested_resources(self, resourceDesc, rootDesc, schema): # Add in nested resources if 'resources' in resourceDesc: def createResourceMethod(methodName, methodDesc): """Create a method on the Resource to access a nested Resource. Args: methodName: string, name of the method to use. methodDesc: object, fragment of deserialized discovery document that describes the method. """ methodName = fix_method_name(methodName) def methodResource(self): return Resource(http=self._http, baseUrl=self._baseUrl, model=self._model, developerKey=self._developerKey, requestBuilder=self._requestBuilder, resourceDesc=methodDesc, rootDesc=rootDesc, schema=schema) setattr(methodResource, '__doc__', 'A collection resource.') setattr(methodResource, '__is_resource__', True) return (methodName, methodResource) for methodName, methodDesc in resourceDesc['resources'].iteritems(): fixedMethodName, method = createResourceMethod(methodName, methodDesc) self._set_dynamic_attr(fixedMethodName, method.__get__(self, self.__class__)) def _add_next_methods(self, resourceDesc, schema): # Add _next() methods # Look for response bodies in schema that contain nextPageToken, and methods # that take a pageToken parameter. if 'methods' in resourceDesc: for methodName, methodDesc in resourceDesc['methods'].iteritems(): if 'response' in methodDesc: responseSchema = methodDesc['response'] if '$ref' in responseSchema: responseSchema = schema.get(responseSchema['$ref']) hasNextPageToken = 'nextPageToken' in responseSchema.get('properties', {}) hasPageToken = 'pageToken' in methodDesc.get('parameters', {}) if hasNextPageToken and hasPageToken: fixedMethodName, method = createNextMethod(methodName + '_next') self._set_dynamic_attr(fixedMethodName, method.__get__(self, self.__class__)) google-api-python-client-1.2/apiclient/schema.py0000640017135500116100000002211312173557443022714 0ustar jcgregorioeng00000000000000# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Schema processing for discovery based APIs Schemas holds an APIs discovery schemas. It can return those schema as deserialized JSON objects, or pretty print them as prototype objects that conform to the schema. For example, given the schema: schema = \"\"\"{ "Foo": { "type": "object", "properties": { "etag": { "type": "string", "description": "ETag of the collection." }, "kind": { "type": "string", "description": "Type of the collection ('calendar#acl').", "default": "calendar#acl" }, "nextPageToken": { "type": "string", "description": "Token used to access the next page of this result. Omitted if no further results are available." } } } }\"\"\" s = Schemas(schema) print s.prettyPrintByName('Foo') Produces the following output: { "nextPageToken": "A String", # Token used to access the # next page of this result. Omitted if no further results are available. "kind": "A String", # Type of the collection ('calendar#acl'). "etag": "A String", # ETag of the collection. }, The constructor takes a discovery document in which to look up named schema. """ # TODO(jcgregorio) support format, enum, minimum, maximum __author__ = 'jcgregorio@google.com (Joe Gregorio)' import copy from oauth2client import util from oauth2client.anyjson import simplejson class Schemas(object): """Schemas for an API.""" def __init__(self, discovery): """Constructor. Args: discovery: object, Deserialized discovery document from which we pull out the named schema. """ self.schemas = discovery.get('schemas', {}) # Cache of pretty printed schemas. self.pretty = {} @util.positional(2) def _prettyPrintByName(self, name, seen=None, dent=0): """Get pretty printed object prototype from the schema name. Args: name: string, Name of schema in the discovery document. 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. """ if seen is None: seen = [] if name in seen: # Do not fall into an infinite loop over recursive definitions. return '# Object with schema name: %s' % name seen.append(name) if name not in self.pretty: self.pretty[name] = _SchemaToStruct(self.schemas[name], seen, dent=dent).to_str(self._prettyPrintByName) seen.pop() return self.pretty[name] def prettyPrintByName(self, name): """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. """ # Return with trailing comma and newline removed. return self._prettyPrintByName(name, seen=[], dent=1)[:-2] @util.positional(2) def _prettyPrintSchema(self, schema, seen=None, dent=0): """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. """ if seen is None: seen = [] return _SchemaToStruct(schema, seen, dent=dent).to_str(self._prettyPrintByName) def prettyPrintSchema(self, schema): """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. """ # Return with trailing comma and newline removed. return self._prettyPrintSchema(schema, dent=1)[:-2] def get(self, name): """Get deserialized JSON schema from the schema name. Args: name: string, Schema name. """ return self.schemas[name] class _SchemaToStruct(object): """Convert schema to a prototype object.""" @util.positional(3) def __init__(self, schema, seen, dent=0): """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. """ # The result of this parsing kept as list of strings. self.value = [] # The final value of the parsing. self.string = None # The parsed JSON schema. self.schema = schema # Indentation level. self.dent = dent # Method that when called returns a prototype object for the schema with # the given name. self.from_cache = None # List of names of schema already seen while parsing. self.seen = seen def emit(self, text): """Add text as a line to the output. Args: text: string, Text to output. """ self.value.extend([" " * self.dent, text, '\n']) def emitBegin(self, text): """Add text to the output, but with no line terminator. Args: text: string, Text to output. """ self.value.extend([" " * self.dent, text]) def emitEnd(self, text, comment): """Add text and comment to the output with line terminator. Args: text: string, Text to output. comment: string, Python 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']) def indent(self): """Increase indentation level.""" self.dent += 1 def undent(self): """Decrease indentation level.""" self.dent -= 1 def _to_str_impl(self, schema): """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. """ stype = schema.get('type') if stype == 'object': self.emitEnd('{', schema.get('description', '')) self.indent() if 'properties' in schema: for pname, pschema in schema.get('properties', {}).iteritems(): self.emitBegin('"%s": ' % pname) self._to_str_impl(pschema) elif 'additionalProperties' in schema: self.emitBegin('"a_key": ') self._to_str_impl(schema['additionalProperties']) self.undent() self.emit('},') elif '$ref' in schema: schemaName = schema['$ref'] description = schema.get('description', '') s = self.from_cache(schemaName, seen=self.seen) parts = s.splitlines() self.emitEnd(parts[0], description) for line in parts[1:]: self.emit(line.rstrip()) elif stype == 'boolean': value = schema.get('default', 'True or False') self.emitEnd('%s,' % str(value), schema.get('description', '')) elif stype == 'string': value = schema.get('default', 'A String') self.emitEnd('"%s",' % str(value), schema.get('description', '')) elif stype == 'integer': value = schema.get('default', '42') self.emitEnd('%s,' % str(value), schema.get('description', '')) elif stype == 'number': value = schema.get('default', '3.14') self.emitEnd('%s,' % str(value), schema.get('description', '')) elif stype == 'null': self.emitEnd('None,', schema.get('description', '')) elif stype == 'any': self.emitEnd('"",', schema.get('description', '')) elif stype == 'array': self.emitEnd('[', schema.get('description')) self.indent() self.emitBegin('') self._to_str_impl(schema['items']) self.undent() self.emit('],') else: self.emit('Unknown type! %s' % stype) self.emitEnd('', '') self.string = ''.join(self.value) return self.string def to_str(self, from_cache): """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 schema, in Python code with comments. The lines of the code will all be properly indented. """ self.from_cache = from_cache return self._to_str_impl(self.schema) google-api-python-client-1.2/apiclient/http.py0000640017135500116100000014715712173557443022453 0ustar jcgregorioeng00000000000000# Copyright (C) 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Classes to encapsulate a single HTTP request. The classes implement a command pattern, with every object supporting an execute() method that does the actuall HTTP request. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import StringIO import base64 import copy import gzip import httplib2 import logging import mimeparse import mimetypes import os import random import sys import time import urllib import urlparse import uuid from email.generator import Generator from email.mime.multipart import MIMEMultipart from email.mime.nonmultipart import MIMENonMultipart from email.parser import FeedParser from errors import BatchError from errors import HttpError from errors import InvalidChunkSizeError from errors import ResumableUploadError from errors import UnexpectedBodyError from errors import UnexpectedMethodError from model import JsonModel from oauth2client import util from oauth2client.anyjson import simplejson DEFAULT_CHUNK_SIZE = 512*1024 MAX_URI_LENGTH = 2048 class MediaUploadProgress(object): """Status of a resumable upload.""" def __init__(self, resumable_progress, total_size): """Constructor. Args: resumable_progress: int, bytes sent so far. total_size: int, total bytes in complete upload, or None if the total upload size isn't known ahead of time. """ self.resumable_progress = resumable_progress self.total_size = total_size def progress(self): """Percent of upload completed, as a float. Returns: the percentage complete as a float, returning 0.0 if the total size of the upload is unknown. """ if self.total_size is not None: return float(self.resumable_progress) / float(self.total_size) else: return 0.0 class MediaDownloadProgress(object): """Status of a resumable download.""" def __init__(self, resumable_progress, total_size): """Constructor. Args: resumable_progress: int, bytes received so far. total_size: int, total bytes in complete download. """ self.resumable_progress = resumable_progress self.total_size = total_size def progress(self): """Percent of download completed, as a float. Returns: the percentage complete as a float, returning 0.0 if the total size of the download is unknown. """ if self.total_size is not None: return float(self.resumable_progress) / float(self.total_size) else: return 0.0 class MediaUpload(object): """Describes a media object to upload. Base class that defines the interface of MediaUpload subclasses. Note that subclasses of MediaUpload may allow you to control the chunksize when uploading a media object. It is important to keep the size of the chunk as large as possible to keep the upload efficient. Other factors may influence the size of the chunk you use, particularly if you are working in an environment where individual HTTP requests may have a hardcoded time limit, such as under certain classes of requests under Google App Engine. Streams are io.Base compatible objects that support seek(). Some MediaUpload subclasses support using streams directly to upload data. Support for streaming may be indicated by a MediaUpload sub-class and if appropriate for a platform that stream will be used for uploading the media object. The support for streaming is indicated by has_stream() returning True. The stream() method should return an io.Base object that supports seek(). On platforms where the underlying httplib module supports streaming, for example Python 2.6 and later, the stream will be passed into the http library which will result in less memory being used and possibly faster uploads. If you need to upload media that can't be uploaded using any of the existing MediaUpload sub-class then you can sub-class MediaUpload for your particular needs. """ def chunksize(self): """Chunk size for resumable uploads. Returns: Chunk size in bytes. """ raise NotImplementedError() def mimetype(self): """Mime type of the body. Returns: Mime type. """ return 'application/octet-stream' def size(self): """Size of upload. Returns: Size of the body, or None of the size is unknown. """ return None def resumable(self): """Whether this upload is resumable. Returns: True if resumable upload or False. """ return False def getbytes(self, begin, end): """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 shorter than length if EOF was reached first. """ raise NotImplementedError() def has_stream(self): """Does the underlying upload support a streaming interface. Streaming means it is an io.IOBase subclass that supports seek, i.e. seekable() returns True. Returns: True if the call to stream() will return an instance of a seekable io.Base subclass. """ return False def stream(self): """A stream interface to the data being uploaded. Returns: The returned value is an io.IOBase subclass that supports seek, i.e. seekable() returns True. """ raise NotImplementedError() @util.positional(1) def _to_json(self, strip=None): """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(). """ 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) def to_json(self): """Create a JSON representation of an instance of MediaUpload. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ return self._to_json() @classmethod def new_from_json(cls, s): """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(). """ data = simplejson.loads(s) # Find and call the right classmethod from_json() to restore the object. 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) class MediaIoBaseUpload(MediaUpload): """A MediaUpload for a io.Base objects. Note that the Python file object is compatible with io.Base and can be used with this class also. fh = io.BytesIO('...Some data to upload...') media = MediaIoBaseUpload(fh, mimetype='image/png', chunksize=1024*1024, resumable=True) farm.animals().insert( id='cow', name='cow.png', media_body=media).execute() Depending on the platform you are working on, you may pass -1 as the chunksize, which indicates that the entire file should be uploaded in a single request. If the underlying platform supports streams, such as Python 2.6 or later, then this can be very efficient as it avoids multiple connections, and also avoids loading the entire file into memory before sending it. Note that Google App Engine has a 5MB limit on request size, so you should never set your chunksize larger than 5MB, or to -1. """ @util.positional(3) def __init__(self, fd, mimetype, chunksize=DEFAULT_CHUNK_SIZE, resumable=False): """Constructor. Args: fd: io.Base or file object, The source of the bytes to upload. MUST be opened in blocking mode, do not use streams opened in non-blocking mode. The given stream must be seekable, that is, it must be able to call seek() on fd. mimetype: string, Mime-type of the file. chunksize: int, File will be uploaded in chunks of this many bytes. Only used if resumable=True. Pass in a value of -1 if the file is to be uploaded as a single chunk. Note that Google App Engine has a 5MB limit on request size, so you should never set your chunksize larger than 5MB, or to -1. resumable: bool, True if this is a resumable upload. False means upload in a single request. """ super(MediaIoBaseUpload, self).__init__() self._fd = fd self._mimetype = mimetype if not (chunksize == -1 or chunksize > 0): raise InvalidChunkSizeError() self._chunksize = chunksize self._resumable = resumable self._fd.seek(0, os.SEEK_END) self._size = self._fd.tell() def chunksize(self): """Chunk size for resumable uploads. Returns: Chunk size in bytes. """ return self._chunksize def mimetype(self): """Mime type of the body. Returns: Mime type. """ return self._mimetype def size(self): """Size of upload. Returns: Size of the body, or None of the size is unknown. """ return self._size def resumable(self): """Whether this upload is resumable. Returns: True if resumable upload or False. """ return self._resumable def getbytes(self, begin, length): """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. """ self._fd.seek(begin) return self._fd.read(length) def has_stream(self): """Does the underlying upload support a streaming interface. Streaming means it is an io.IOBase subclass that supports seek, i.e. seekable() returns True. Returns: True if the call to stream() will return an instance of a seekable io.Base subclass. """ return True def stream(self): """A stream interface to the data being uploaded. Returns: The returned value is an io.IOBase subclass that supports seek, i.e. seekable() returns True. """ return self._fd def to_json(self): """This upload type is not serializable.""" raise NotImplementedError('MediaIoBaseUpload is not serializable.') class MediaFileUpload(MediaIoBaseUpload): """A MediaUpload for a file. Construct a MediaFileUpload and pass as the media_body parameter of the method. For example, if we had a service that allowed uploading images: media = MediaFileUpload('cow.png', mimetype='image/png', chunksize=1024*1024, resumable=True) farm.animals().insert( id='cow', name='cow.png', media_body=media).execute() Depending on the platform you are working on, you may pass -1 as the chunksize, which indicates that the entire file should be uploaded in a single request. If the underlying platform supports streams, such as Python 2.6 or later, then this can be very efficient as it avoids multiple connections, and also avoids loading the entire file into memory before sending it. Note that Google App Engine has a 5MB limit on request size, so you should never set your chunksize larger than 5MB, or to -1. """ @util.positional(2) def __init__(self, filename, mimetype=None, chunksize=DEFAULT_CHUNK_SIZE, resumable=False): """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. Pass in a value of -1 if the file is to be uploaded in a single chunk. Note that Google App Engine has a 5MB limit on request size, so you should never set your chunksize larger than 5MB, or to -1. resumable: bool, True if this is a resumable upload. False means upload in a single request. """ self._filename = filename fd = open(self._filename, 'rb') if mimetype is None: (mimetype, encoding) = mimetypes.guess_type(filename) super(MediaFileUpload, self).__init__(fd, mimetype, chunksize=chunksize, resumable=resumable) def to_json(self): """Creating a JSON representation of an instance of MediaFileUpload. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ return self._to_json(strip=['_fd']) @staticmethod def from_json(s): d = simplejson.loads(s) return MediaFileUpload(d['_filename'], mimetype=d['_mimetype'], chunksize=d['_chunksize'], resumable=d['_resumable']) class MediaInMemoryUpload(MediaIoBaseUpload): """MediaUpload for a chunk of bytes. DEPRECATED: Use MediaIoBaseUpload with either io.TextIOBase or StringIO for the stream. """ @util.positional(2) def __init__(self, body, mimetype='application/octet-stream', chunksize=DEFAULT_CHUNK_SIZE, resumable=False): """Create a new MediaInMemoryUpload. DEPRECATED: Use MediaIoBaseUpload with either io.TextIOBase or StringIO for the stream. Args: body: string, Bytes of body content. mimetype: string, Mime-type of the file or default of 'application/octet-stream'. 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 means upload in a single request. """ fd = StringIO.StringIO(body) super(MediaInMemoryUpload, self).__init__(fd, mimetype, chunksize=chunksize, resumable=resumable) class MediaIoBaseDownload(object): """"Download media resources. Note that the Python file object is compatible with io.Base and can be used with this class also. Example: request = farms.animals().get_media(id='cow') fh = io.FileIO('cow.png', mode='wb') downloader = MediaIoBaseDownload(fh, request, chunksize=1024*1024) done = False while done is False: status, done = downloader.next_chunk() if status: print "Download %d%%." % int(status.progress() * 100) print "Download Complete!" """ @util.positional(3) def __init__(self, fd, request, chunksize=DEFAULT_CHUNK_SIZE): """Constructor. Args: fd: io.Base or file object, The stream in which to write the downloaded bytes. request: apiclient.http.HttpRequest, the media request to perform in chunks. chunksize: int, File will be downloaded in chunks of this many bytes. """ self._fd = fd self._request = request self._uri = request.uri self._chunksize = chunksize self._progress = 0 self._total_size = None self._done = False # Stubs for testing. self._sleep = time.sleep self._rand = random.random @util.positional(1) def next_chunk(self, num_retries=0): """Get the next chunk of the download. Args: num_retries: Integer, number of times to retry 500's with randomized exponential backoff. If all retries fail, the raised HttpError represents the last request. If zero (default), we attempt the request only once. Returns: (status, done): (MediaDownloadStatus, boolean) The value of 'done' will be True when the media has been fully downloaded. Raises: apiclient.errors.HttpError if the response was not a 2xx. httplib2.HttpLib2Error if a transport error has occured. """ headers = { 'range': 'bytes=%d-%d' % ( self._progress, self._progress + self._chunksize) } http = self._request.http for retry_num in xrange(num_retries + 1): if retry_num > 0: self._sleep(self._rand() * 2**retry_num) logging.warning( 'Retry #%d for media download: GET %s, following status: %d' % (retry_num, self._uri, resp.status)) resp, content = http.request(self._uri, headers=headers) if resp.status < 500: break if resp.status in [200, 206]: if 'content-location' in resp and resp['content-location'] != self._uri: self._uri = resp['content-location'] self._progress += len(content) self._fd.write(content) if 'content-range' in resp: content_range = resp['content-range'] length = content_range.rsplit('/', 1)[1] self._total_size = int(length) if self._progress == self._total_size: self._done = True return MediaDownloadProgress(self._progress, self._total_size), self._done else: raise HttpError(resp, content, uri=self._uri) class _StreamSlice(object): """Truncated stream. Takes a stream and presents a stream that is a slice of the original stream. This is used when uploading media in chunks. In later versions of Python a stream can be passed to httplib in place of the string of data to send. The problem is that httplib just blindly reads to the end of the stream. This wrapper presents a virtual stream that only reads to the end of the chunk. """ def __init__(self, stream, begin, chunksize): """Constructor. Args: stream: (io.Base, file object), the stream to wrap. begin: int, the seek position the chunk begins at. chunksize: int, the size of the chunk. """ self._stream = stream self._begin = begin self._chunksize = chunksize self._stream.seek(begin) def read(self, n=-1): """Read n bytes. Args: n, int, the number of bytes to read. Returns: A string of length 'n', or less if EOF is reached. """ # The data left available to read sits in [cur, end) cur = self._stream.tell() end = self._begin + self._chunksize if n == -1 or cur + n > end: n = end - cur return self._stream.read(n) class HttpRequest(object): """Encapsulates a single HTTP request.""" @util.positional(4) def __init__(self, http, postproc, uri, method='GET', body=None, headers=None, methodId=None, resumable=None): """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: string, the HTTP method to use body: string, the request body of the HTTP request, headers: dict, the HTTP request headers methodId: string, a unique identifier for the API method being called. resumable: MediaUpload, None if this is not a resumbale request. """ 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 self.response_callbacks = [] self._in_error_state = False # Pull the multipart boundary out of the content-type header. major, minor, params = mimeparse.parse_mime_type( headers.get('content-type', 'application/json')) # The size of the non-media part of the request. self.body_size = len(self.body or '') # The resumable URI to send chunks to. self.resumable_uri = None # The bytes that have been uploaded. self.resumable_progress = 0 # Stubs for testing. self._rand = random.random self._sleep = time.sleep @util.positional(1) def execute(self, http=None, num_retries=0): """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. num_retries: Integer, number of times to retry 500's with randomized exponential backoff. If all retries fail, the raised HttpError represents the last request. If zero (default), we attempt the request only once. 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.HttpLib2Error if a transport error has occured. """ if http is None: http = self.http if self.resumable: body = None while body is None: _, body = self.next_chunk(http=http, num_retries=num_retries) return body # Non-resumable case. if 'content-length' not in self.headers: self.headers['content-length'] = str(self.body_size) # If the request URI is too long then turn it into a POST request. if len(self.uri) > MAX_URI_LENGTH and self.method == 'GET': self.method = 'POST' self.headers['x-http-method-override'] = 'GET' self.headers['content-type'] = 'application/x-www-form-urlencoded' parsed = urlparse.urlparse(self.uri) self.uri = urlparse.urlunparse( (parsed.scheme, parsed.netloc, parsed.path, parsed.params, None, None) ) self.body = parsed.query self.headers['content-length'] = str(len(self.body)) # Handle retries for server-side errors. for retry_num in xrange(num_retries + 1): if retry_num > 0: self._sleep(self._rand() * 2**retry_num) logging.warning('Retry #%d for request: %s %s, following status: %d' % (retry_num, self.method, self.uri, resp.status)) resp, content = http.request(str(self.uri), method=str(self.method), body=self.body, headers=self.headers) if resp.status < 500: break for callback in self.response_callbacks: callback(resp) if resp.status >= 300: raise HttpError(resp, content, uri=self.uri) return self.postproc(resp, content) @util.positional(2) def add_response_callback(self, cb): """add_response_headers_callback Args: cb: Callback to be called on receiving the response headers, of signature: def cb(resp): # Where resp is an instance of httplib2.Response """ self.response_callbacks.append(cb) @util.positional(1) def next_chunk(self, http=None, num_retries=0): """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('cow.png', mimetype='image/png', chunksize=1000, resumable=True) request = farm.animals().insert( id='cow', name='cow.png', media_body=media) response = None while response is None: status, response = request.next_chunk() if status: print "Upload %d%% complete." % int(status.progress() * 100) Args: http: httplib2.Http, an http object to be used in place of the one the HttpRequest request object was constructed with. num_retries: Integer, number of times to retry 500's with randomized exponential backoff. If all retries fail, the raised HttpError represents the last request. If zero (default), we attempt the request only once. Returns: (status, body): (ResumableMediaStatus, object) The body will be None until the resumable media is fully uploaded. Raises: apiclient.errors.HttpError if the response was not a 2xx. httplib2.HttpLib2Error if a transport error has occured. """ if http is None: http = self.http if self.resumable.size() is None: size = '*' else: size = str(self.resumable.size()) if self.resumable_uri is None: start_headers = copy.copy(self.headers) start_headers['X-Upload-Content-Type'] = self.resumable.mimetype() if size != '*': start_headers['X-Upload-Content-Length'] = size start_headers['content-length'] = str(self.body_size) for retry_num in xrange(num_retries + 1): if retry_num > 0: self._sleep(self._rand() * 2**retry_num) logging.warning( 'Retry #%d for resumable URI request: %s %s, following status: %d' % (retry_num, self.method, self.uri, resp.status)) resp, content = http.request(self.uri, method=self.method, body=self.body, headers=start_headers) if resp.status < 500: break if resp.status == 200 and 'location' in resp: self.resumable_uri = resp['location'] else: raise ResumableUploadError(resp, content) elif self._in_error_state: # If we are in an error state then query the server for current state of # the upload by sending an empty PUT and reading the 'range' header in # the response. headers = { 'Content-Range': 'bytes */%s' % size, 'content-length': '0' } resp, content = http.request(self.resumable_uri, 'PUT', headers=headers) status, body = self._process_response(resp, content) if body: # The upload was complete. return (status, body) # The httplib.request method can take streams for the body parameter, but # only in Python 2.6 or later. If a stream is available under those # conditions then use it as the body argument. if self.resumable.has_stream() and sys.version_info[1] >= 6: data = self.resumable.stream() if self.resumable.chunksize() == -1: data.seek(self.resumable_progress) chunk_end = self.resumable.size() - self.resumable_progress - 1 else: # Doing chunking with a stream, so wrap a slice of the stream. data = _StreamSlice(data, self.resumable_progress, self.resumable.chunksize()) chunk_end = min( self.resumable_progress + self.resumable.chunksize() - 1, self.resumable.size() - 1) else: data = self.resumable.getbytes( self.resumable_progress, self.resumable.chunksize()) # A short read implies that we are at EOF, so finish the upload. if len(data) < self.resumable.chunksize(): size = str(self.resumable_progress + len(data)) chunk_end = self.resumable_progress + len(data) - 1 headers = { 'Content-Range': 'bytes %d-%d/%s' % ( self.resumable_progress, chunk_end, size), # Must set the content-length header here because httplib can't # calculate the size when working with _StreamSlice. 'Content-Length': str(chunk_end - self.resumable_progress + 1) } for retry_num in xrange(num_retries + 1): if retry_num > 0: self._sleep(self._rand() * 2**retry_num) logging.warning( 'Retry #%d for media upload: %s %s, following status: %d' % (retry_num, self.method, self.uri, resp.status)) try: resp, content = http.request(self.resumable_uri, method='PUT', body=data, headers=headers) except: self._in_error_state = True raise if resp.status < 500: break return self._process_response(resp, content) def _process_response(self, resp, content): """Process the response from a single chunk upload. Args: resp: httplib2.Response, the response object. content: string, the content of the response. Returns: (status, body): (ResumableMediaStatus, object) The body will be None until the resumable media is fully uploaded. Raises: apiclient.errors.HttpError if the response was not a 2xx or a 308. """ if resp.status in [200, 201]: self._in_error_state = False return None, self.postproc(resp, content) elif resp.status == 308: self._in_error_state = False # A "308 Resume Incomplete" indicates we are not done. self.resumable_progress = int(resp['range'].split('-')[1]) + 1 if 'location' in resp: self.resumable_uri = resp['location'] else: self._in_error_state = True raise HttpError(resp, content, uri=self.uri) return (MediaUploadProgress(self.resumable_progress, self.resumable.size()), None) def to_json(self): """Returns a JSON representation of the HttpRequest.""" d = copy.copy(self.__dict__) if d['resumable'] is not None: d['resumable'] = self.resumable.to_json() del d['http'] del d['postproc'] del d['_sleep'] del d['_rand'] return simplejson.dumps(d) @staticmethod def from_json(s, http, postproc): """Returns an HttpRequest populated with info from a JSON object.""" 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']) class BatchHttpRequest(object): """Batches multiple HttpRequest objects into a single HTTP request. Example: from apiclient.http import BatchHttpRequest def list_animals(request_id, response, exception): \"\"\"Do something with the animals list response.\"\"\" if exception is not None: # Do something with the exception. pass else: # Do something with the response. pass def list_farmers(request_id, response, exception): \"\"\"Do something with the farmers list response.\"\"\" if exception is not None: # Do something with the exception. pass else: # Do something with the response. pass service = build('farm', 'v2') batch = BatchHttpRequest() batch.add(service.animals().list(), list_animals) batch.add(service.farmers().list(), list_farmers) batch.execute(http=http) """ @util.positional(1) def __init__(self, callback=None, batch_uri=None): """Constructor for a BatchHttpRequest. Args: callback: callable, A callback to be called for each response, of the form callback(id, response, exception). The first parameter is the request id, and the second is the deserialized response object. The third is an apiclient.errors.HttpError exception object if an HTTP error occurred while processing the request, or None if no error occurred. batch_uri: string, URI to send batch requests to. """ if batch_uri is None: batch_uri = 'https://www.googleapis.com/batch' self._batch_uri = batch_uri # Global callback to be called for each individual response in the batch. self._callback = callback # A map from id to request. self._requests = {} # A map from id to callback. self._callbacks = {} # List of request ids, in the order in which they were added. self._order = [] # The last auto generated id. self._last_auto_id = 0 # Unique ID on which to base the Content-ID headers. self._base_id = None # A map from request id to (httplib2.Response, content) response pairs self._responses = {} # A map of id(Credentials) that have been refreshed. self._refreshed_credentials = {} def _refresh_and_apply_credentials(self, request, http): """Refresh the credentials and apply to the request. Args: request: HttpRequest, the request. http: httplib2.Http, the global http object for the batch. """ # For the credentials to refresh, but only once per refresh_token # If there is no http per the request then refresh the http passed in # via execute() creds = None if request.http is not None and hasattr(request.http.request, 'credentials'): creds = request.http.request.credentials elif http is not None and hasattr(http.request, 'credentials'): creds = http.request.credentials if creds is not None: if id(creds) not in self._refreshed_credentials: creds.refresh(http) self._refreshed_credentials[id(creds)] = 1 # Only apply the credentials if we are using the http object passed in, # otherwise apply() will get called during _serialize_request(). if request.http is None or not hasattr(request.http.request, 'credentials'): creds.apply(request.headers) def _id_to_header(self, id_): """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. """ if self._base_id is None: self._base_id = uuid.uuid4() return '<%s+%s>' % (self._base_id, urllib.quote(id_)) def _header_to_id(self, header): """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. """ 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.unquote(id_) def _serialize_request(self, request): """Convert an HttpRequest object into a string. Args: request: HttpRequest, the request to serialize. Returns: The request as a string in application/http format. """ # Construct status line 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('/') msg = MIMENonMultipart(major, minor) headers = request.headers.copy() if request.http is not None and hasattr(request.http.request, 'credentials'): request.http.request.credentials.apply(headers) # MIMENonMultipart adds its own Content-Type header. if 'content-type' in headers: del headers['content-type'] for key, value in headers.iteritems(): msg[key] = value msg['Host'] = parsed.netloc msg.set_unixfrom(None) if request.body is not None: msg.set_payload(request.body) msg['content-length'] = str(len(request.body)) # Serialize the mime message. fp = StringIO.StringIO() # maxheaderlen=0 means don't line wrap headers. g = Generator(fp, maxheaderlen=0) g.flatten(msg, unixfrom=False) body = fp.getvalue() # Strip off the \n\n that the MIME lib tacks onto the end of the payload. if request.body is None: body = body[:-2] return status_line.encode('utf-8') + body def _deserialize_response(self, payload): """Convert string into httplib2 response and content. Args: payload: string, headers and body as a string. Returns: A pair (resp, content), such as would be returned from httplib2.request. """ # Strip off the status line status_line, payload = payload.split('\n', 1) protocol, status, reason = status_line.split(' ', 2) # Parse the rest of the response parser = FeedParser() parser.feed(payload) msg = parser.close() msg['status'] = status # Create httplib2.Response from the parsed headers. resp = httplib2.Response(msg) resp.reason = reason resp.version = int(protocol.split('/', 1)[1].replace('.', '')) content = payload.split('\r\n\r\n', 1)[1] return resp, content def _new_id(self): """Create a new id. Auto incrementing number that avoids conflicts with ids already used. Returns: string, a new unique id. """ 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) @util.positional(2) def add(self, request, callback=None, request_id=None): """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 uniqueness for each request_id, and if they are not an exception is raised. Callers should either supply all request_ids or nevery supply a request id, to avoid such an error. Args: request: HttpRequest, Request to add to the batch. callback: callable, A callback to be called for this response, of the form callback(id, response, exception). The first parameter is the request id, and the second is the deserialized response object. The third is an apiclient.errors.HttpError exception object if an HTTP error occurred while processing the request, or None if no errors occurred. request_id: string, A unique id for the request. The id will be passed to the callback with the response. Returns: None Raises: BatchError if a media request is added to a batch. KeyError is the request_id is not unique. """ if request_id is None: request_id = self._new_id() if request.resumable is not None: raise BatchError("Media requests cannot be used in a batch request.") if request_id in self._requests: raise KeyError("A request with this ID already exists: %s" % request_id) self._requests[request_id] = request self._callbacks[request_id] = callback self._order.append(request_id) def _execute(self, http, order, requests): """Serialize batch request, send to server, process response. Args: http: httplib2.Http, an http object to be used to make the request with. order: list, list of request ids in the order they were added to the batch. request: list, list of request objects to send. Raises: httplib2.HttpLib2Error if a transport error has occured. apiclient.errors.BatchError if the response is the wrong format. """ message = MIMEMultipart('mixed') # Message should not write out it's own headers. setattr(message, '_write_headers', lambda self: None) # Add all the individual requests. for request_id in order: request = requests[request_id] msg = MIMENonMultipart('application', 'http') msg['Content-Transfer-Encoding'] = 'binary' msg['Content-ID'] = self._id_to_header(request_id) body = self._serialize_request(request) msg.set_payload(body) message.attach(msg) body = message.as_string() headers = {} headers['content-type'] = ('multipart/mixed; ' 'boundary="%s"') % message.get_boundary() resp, content = http.request(self._batch_uri, method='POST', body=body, headers=headers) if resp.status >= 300: raise HttpError(resp, content, uri=self._batch_uri) # Now break out the individual responses and store each one. boundary, _ = content.split(None, 1) # Prepend with a content-type header so FeedParser can handle it. header = 'content-type: %s\r\n\r\n' % resp['content-type'] for_parser = header + content parser = FeedParser() parser.feed(for_parser) mime_response = parser.close() if not mime_response.is_multipart(): raise BatchError("Response not in multipart/mixed format.", resp=resp, content=content) for part in mime_response.get_payload(): request_id = self._header_to_id(part['Content-ID']) response, content = self._deserialize_response(part.get_payload()) self._responses[request_id] = (response, content) @util.positional(1) def execute(self, http=None): """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: httplib2.HttpLib2Error if a transport error has occured. apiclient.errors.BatchError if the response is the wrong format. """ # If http is not supplied use the first valid one given in the requests. if http is None: for request_id in self._order: request = self._requests[request_id] if request is not None: http = request.http break if http is None: raise ValueError("Missing a valid http object.") self._execute(http, self._order, self._requests) # Loop over all the requests and check for 401s. For each 401 request the # credentials should be refreshed and then sent again in a separate batch. redo_requests = {} redo_order = [] for request_id in self._order: resp, content = self._responses[request_id] if resp['status'] == '401': redo_order.append(request_id) request = self._requests[request_id] self._refresh_and_apply_credentials(request, http) redo_requests[request_id] = request if redo_requests: self._execute(http, redo_order, redo_requests) # Now process all callbacks that are erroring, and raise an exception for # ones that return a non-2xx response? Or add extra parameter to callback # that contains an HttpError? for request_id in self._order: resp, content = self._responses[request_id] request = self._requests[request_id] callback = self._callbacks[request_id] response = None exception = None try: if resp.status >= 300: raise HttpError(resp, content, uri=request.uri) response = request.postproc(resp, content) except HttpError, e: exception = e if callback is not None: callback(request_id, response, exception) if self._callback is not None: self._callback(request_id, response, exception) class HttpRequestMock(object): """Mock of HttpRequest. Do not construct directly, instead use RequestMockBuilder. """ def __init__(self, resp, content, postproc): """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. """ 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'] def execute(self, http=None): """Execute the request. Same behavior as HttpRequest.execute(), but the response is mocked and not really from an HTTP request/response. """ return self.postproc(self.resp, self.content) class RequestMockBuilder(object): """A simple mock of HttpRequest Pass in a dictionary to the constructor that maps request methodIds to tuples of (httplib2.Response, content, opt_expected_body) that should be returned when that method is called. None may also be passed in for the httplib2.Response, in which case a 200 OK response will be generated. If an opt_expected_body (str or dict) is provided, it will be compared to the body and UnexpectedBodyError will be raised on inequality. Example: response = '{"data": {"id": "tag:google.c...' requestBuilder = RequestMockBuilder( { 'plus.activities.get': (None, response), } ) apiclient.discovery.build("plus", "v1", requestBuilder=requestBuilder) Methods that you do not supply a response for will return a 200 OK with an empty string as the response content or raise an excpetion if check_unexpected is set to True. The methodId is taken from the rpcName in the discovery document. For more details see the project wiki. """ def __init__(self, responses, check_unexpected=False): """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 setting whether or not UnexpectedMethodError should be raised on unsupplied method. """ self.responses = responses self.check_unexpected = check_unexpected def __call__(self, http, postproc, uri, method='GET', body=None, headers=None, methodId=None, resumable=None): """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. """ if methodId in self.responses: response = self.responses[methodId] resp, content = response[:2] if len(response) > 2: # Test the body against the supplied expected_body. expected_body = response[2] if bool(expected_body) != bool(body): # Not expecting a body and provided one # or expecting a body and not provided one. raise UnexpectedBodyError(expected_body, body) if isinstance(expected_body, str): expected_body = simplejson.loads(expected_body) body = simplejson.loads(body) if body != expected_body: raise UnexpectedBodyError(expected_body, body) return HttpRequestMock(resp, content, postproc) elif self.check_unexpected: raise UnexpectedMethodError(methodId=methodId) else: model = JsonModel(False) return HttpRequestMock(None, '{}', model.response) class HttpMock(object): """Mock of httplib2.Http""" def __init__(self, filename=None, headers=None): """ Args: filename: string, absolute filename to read response from headers: dict, header to return with response """ if headers is None: headers = {'status': '200 OK'} if filename: f = file(filename, 'r') self.data = f.read() f.close() else: self.data = None self.response_headers = headers self.headers = None self.uri = None self.method = None self.body = None self.headers = None def request(self, uri, method='GET', body=None, headers=None, redirections=1, connection_type=None): self.uri = uri self.method = method self.body = body self.headers = headers return httplib2.Response(self.response_headers), self.data class HttpMockSequence(object): """Mock of httplib2.Http Mocks a sequence of calls to request returning different responses for each call. Create an instance initialized with the desired response headers and content and then use as if an httplib2.Http instance. http = HttpMockSequence([ ({'status': '401'}, ''), ({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'), ({'status': '200'}, 'echo_request_headers'), ]) resp, content = http.request("http://examples.com") There are special values you can pass in for content to trigger behavours that are helpful in testing. 'echo_request_headers' means return the request headers in the response body 'echo_request_headers_as_json' means return the request headers in the response body 'echo_request_body' means return the request body in the response body 'echo_request_uri' means return the request uri in the response body """ def __init__(self, iterable): """ Args: iterable: iterable, a sequence of pairs of (headers, body) """ self._iterable = iterable self.follow_redirects = True def request(self, uri, method='GET', body=None, headers=None, redirections=1, connection_type=None): resp, content = self._iterable.pop(0) if content == 'echo_request_headers': content = headers elif content == 'echo_request_headers_as_json': content = simplejson.dumps(headers) elif content == 'echo_request_body': if hasattr(body, 'read'): content = body.read() else: content = body elif content == 'echo_request_uri': content = uri return httplib2.Response(resp), content def set_user_agent(http, user_agent): """Set the user-agent on every request. Args: http - An instance of httplib2.Http or something that acts like it. user_agent: string, the value for the user-agent header. Returns: A modified instance of http that was passed in. Example: h = httplib2.Http() h = set_user_agent(h, "my-app-name/6.0") Most of the time the user-agent will be set doing auth, this is for the rare cases where you are accessing an unauthenticated endpoint. """ request_orig = http.request # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): """Modify the request headers to add the user-agent.""" if headers is None: headers = {} if 'user-agent' in headers: headers['user-agent'] = user_agent + ' ' + headers['user-agent'] else: headers['user-agent'] = user_agent resp, content = request_orig(uri, method, body, headers, redirections, connection_type) return resp, content http.request = new_request return http def tunnel_patch(http): """Tunnel PATCH requests over POST. 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 = tunnel_patch(h, "my-app-name/6.0") Useful if you are running on a platform that doesn't support PATCH. Apply this last if you are using OAuth 1.0, as changing the method will result in a different signature. """ request_orig = http.request # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): """Modify the request headers to add the user-agent.""" if headers is None: headers = {} if method == 'PATCH': if 'oauth_token' in headers.get('authorization', ''): logging.warning( 'OAuth 1.0 request made with Credentials after tunnel_patch.') headers['x-http-method-override'] = "PATCH" method = 'POST' resp, content = request_orig(uri, method, body, headers, redirections, connection_type) return resp, content http.request = new_request return http google-api-python-client-1.2/apiclient/__init__.py0000640017135500116100000000113112173557442023207 0ustar jcgregorioeng00000000000000# Copyright (C) 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __version__ = "1.2" google-api-python-client-1.2/apiclient/channel.py0000640017135500116100000002317012173557442023067 0ustar jcgregorioeng00000000000000"""Channel notifications support. Classes and functions to support channel subscriptions and notifications on those channels. Notes: - This code is based on experimental APIs and is subject to change. - Notification does not do deduplication of notification ids, that's up to the receiver. - Storing the Channel between calls is up to the caller. Example setting up a channel: # Create a new channel that gets notifications via webhook. channel = new_webhook_channel("https://example.com/my_web_hook") # Store the channel, keyed by 'channel.id'. Store it before calling the # watch method because notifications may start arriving before the watch # method returns. ... resp = service.objects().watchAll( bucket="some_bucket_id", body=channel.body()).execute() channel.update(resp) # Store the channel, keyed by 'channel.id'. Store it after being updated # since the resource_id value will now be correct, and that's needed to # stop a subscription. ... An example Webhook implementation using webapp2. Note that webapp2 puts headers in a case insensitive dictionary, as headers aren't guaranteed to always be upper case. id = self.request.headers[X_GOOG_CHANNEL_ID] # Retrieve the channel by id. channel = ... # Parse notification from the headers, including validating the id. n = notification_from_headers(channel, self.request.headers) # Do app specific stuff with the notification here. if n.resource_state == 'sync': # Code to handle sync state. elif n.resource_state == 'exists': # Code to handle the exists state. elif n.resource_state == 'not_exists': # Code to handle the not exists state. Example of unsubscribing. service.channels().stop(channel.body()) """ import datetime import uuid from apiclient import errors from oauth2client import util # The unix time epoch starts at midnight 1970. EPOCH = datetime.datetime.utcfromtimestamp(0) # Map the names of the parameters in the JSON channel description to # the parameter names we use in the Channel class. CHANNEL_PARAMS = { 'address': 'address', 'id': 'id', 'expiration': 'expiration', 'params': 'params', 'resourceId': 'resource_id', 'resourceUri': 'resource_uri', 'type': 'type', 'token': 'token', } X_GOOG_CHANNEL_ID = 'X-GOOG-CHANNEL-ID' X_GOOG_MESSAGE_NUMBER = 'X-GOOG-MESSAGE-NUMBER' X_GOOG_RESOURCE_STATE = 'X-GOOG-RESOURCE-STATE' X_GOOG_RESOURCE_URI = 'X-GOOG-RESOURCE-URI' X_GOOG_RESOURCE_ID = 'X-GOOG-RESOURCE-ID' def _upper_header_keys(headers): new_headers = {} for k, v in headers.iteritems(): new_headers[k.upper()] = v return new_headers class Notification(object): """A Notification from a Channel. Notifications are not usually constructed directly, but are returned from functions like notification_from_headers(). Attributes: message_number: int, The unique id number of this notification. state: str, The state of the resource being monitored. uri: str, The address of the resource being monitored. resource_id: str, The unique identifier of the version of the resource at this event. """ @util.positional(5) def __init__(self, message_number, state, resource_uri, resource_id): """Notification constructor. Args: message_number: int, The unique id number of this notification. state: str, The state of the resource being monitored. Can be one of "exists", "not_exists", or "sync". resource_uri: str, The address of the resource being monitored. resource_id: str, The identifier of the watched resource. """ self.message_number = message_number self.state = state self.resource_uri = resource_uri self.resource_id = resource_id class Channel(object): """A Channel for notifications. Usually not constructed directly, instead it is returned from helper functions like new_webhook_channel(). Attributes: type: str, The type of delivery mechanism used by this channel. For example, 'web_hook'. id: str, A UUID for the channel. token: str, An arbitrary string associated with the channel that is delivered to the target address with each event delivered over this channel. address: str, The address of the receiving entity where events are delivered. Specific to the channel type. expiration: int, The time, in milliseconds from the epoch, when this channel will expire. params: dict, A dictionary of string to string, with additional parameters controlling delivery channel behavior. resource_id: str, An opaque id that identifies the resource that is being watched. Stable across different API versions. resource_uri: str, The canonicalized ID of the watched resource. """ @util.positional(5) def __init__(self, type, id, token, address, expiration=None, params=None, resource_id="", resource_uri=""): """Create a new Channel. In user code, this Channel constructor will not typically be called manually since there are functions for creating channels for each specific type with a more customized set of arguments to pass. Args: type: str, The type of delivery mechanism used by this channel. For example, 'web_hook'. id: str, A UUID for the channel. token: str, An arbitrary string associated with the channel that is delivered to the target address with each event delivered over this channel. address: str, The address of the receiving entity where events are delivered. Specific to the channel type. expiration: int, The time, in milliseconds from the epoch, when this channel will expire. params: dict, A dictionary of string to string, with additional parameters controlling delivery channel behavior. resource_id: str, An opaque id that identifies the resource that is being watched. Stable across different API versions. resource_uri: str, The canonicalized ID of the watched resource. """ self.type = type self.id = id self.token = token self.address = address self.expiration = expiration self.params = params self.resource_id = resource_id self.resource_uri = resource_uri def body(self): """Build a body from the Channel. Constructs a dictionary that's appropriate for passing into watch() methods as the value of body argument. Returns: A dictionary representation of the channel. """ result = { 'id': self.id, 'token': self.token, 'type': self.type, 'address': self.address } if self.params: result['params'] = self.params if self.resource_id: result['resourceId'] = self.resource_id if self.resource_uri: result['resourceUri'] = self.resource_uri if self.expiration: result['expiration'] = self.expiration return result def update(self, resp): """Update a channel with information from the response of watch(). When a request is sent to watch() a resource, the response returned from the watch() request is a dictionary with updated channel information, such as the resource_id, which is needed when stopping a subscription. Args: resp: dict, The response from a watch() method. """ for json_name, param_name in CHANNEL_PARAMS.iteritems(): value = resp.get(json_name) if value is not None: setattr(self, param_name, value) def notification_from_headers(channel, headers): """Parse a notification from the webhook request headers, validate the notification, and return a Notification object. Args: channel: Channel, The channel that the notification is associated with. headers: dict, A dictionary like object that contains the request headers from the webhook HTTP request. Returns: A Notification object. Raises: errors.InvalidNotificationError if the notification is invalid. ValueError if the X-GOOG-MESSAGE-NUMBER can't be converted to an int. """ headers = _upper_header_keys(headers) channel_id = headers[X_GOOG_CHANNEL_ID] if channel.id != channel_id: raise errors.InvalidNotificationError( 'Channel id mismatch: %s != %s' % (channel.id, channel_id)) else: message_number = int(headers[X_GOOG_MESSAGE_NUMBER]) state = headers[X_GOOG_RESOURCE_STATE] resource_uri = headers[X_GOOG_RESOURCE_URI] resource_id = headers[X_GOOG_RESOURCE_ID] return Notification(message_number, state, resource_uri, resource_id) @util.positional(2) def new_webhook_channel(url, token=None, expiration=None, params=None): """Create a new webhook Channel. Args: url: str, URL to post notifications to. token: str, An arbitrary string associated with the channel that is delivered to the target address with each notification delivered over this channel. expiration: datetime.datetime, A time in the future when the channel should expire. Can also be None if the subscription should use the default expiration. Note that different services may have different limits on how long a subscription lasts. Check the response from the watch() method to see the value the service has set for an expiration time. params: dict, Extra parameters to pass on channel creation. Currently not used for webhook channels. """ expiration_ms = 0 if expiration: delta = expiration - EPOCH expiration_ms = delta.microseconds/1000 + ( delta.seconds + delta.days*24*3600)*1000 if expiration_ms < 0: expiration_ms = 0 return Channel('web_hook', str(uuid.uuid4()), token, url, expiration=expiration_ms, params=params) google-api-python-client-1.2/google_api_python_client.egg-info/0000750017135500116100000000000012200467672025663 5ustar jcgregorioeng00000000000000google-api-python-client-1.2/google_api_python_client.egg-info/dependency_links.txt0000640017135500116100000000000112200467672031732 0ustar jcgregorioeng00000000000000 google-api-python-client-1.2/google_api_python_client.egg-info/SOURCES.txt0000640017135500116100000000162512200467672027554 0ustar jcgregorioeng00000000000000CHANGELOG FAQ LICENSE MANIFEST.in README setpath.sh setup.py apiclient/__init__.py apiclient/channel.py apiclient/discovery.py apiclient/errors.py apiclient/http.py apiclient/mimeparse.py apiclient/model.py apiclient/sample_tools.py apiclient/schema.py google_api_python_client.egg-info/PKG-INFO google_api_python_client.egg-info/SOURCES.txt google_api_python_client.egg-info/dependency_links.txt google_api_python_client.egg-info/requires.txt google_api_python_client.egg-info/top_level.txt oauth2client/__init__.py oauth2client/anyjson.py oauth2client/appengine.py oauth2client/client.py oauth2client/clientsecrets.py oauth2client/crypt.py oauth2client/django_orm.py oauth2client/file.py oauth2client/gce.py oauth2client/keyring_storage.py oauth2client/locked_file.py oauth2client/multistore_file.py oauth2client/old_run.py oauth2client/tools.py oauth2client/util.py oauth2client/xsrfutil.py uritemplate/__init__.pygoogle-api-python-client-1.2/google_api_python_client.egg-info/requires.txt0000640017135500116100000000001512200467672030260 0ustar jcgregorioeng00000000000000httplib2>=0.8google-api-python-client-1.2/google_api_python_client.egg-info/top_level.txt0000640017135500116100000000004312200467672030413 0ustar jcgregorioeng00000000000000oauth2client apiclient uritemplate google-api-python-client-1.2/google_api_python_client.egg-info/PKG-INFO0000640017135500116100000000124512200467672026763 0ustar jcgregorioeng00000000000000Metadata-Version: 1.1 Name: google-api-python-client Version: 1.2 Summary: Google API Client Library for Python Home-page: http://code.google.com/p/google-api-python-client/ Author: Joe Gregorio Author-email: jcgregorio@google.com License: Apache 2.0 Description: The Google API Client for Python is a client library for accessing the Plus, Moderator, and many other Google APIs. Keywords: google api client Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Apache Software License Classifier: Operating System :: POSIX Classifier: Topic :: Internet :: WWW/HTTP google-api-python-client-1.2/FAQ0000640017135500116100000000037412173557442017470 0ustar jcgregorioeng00000000000000Frequently asked questions? Q: How do I work out the arguments and methods that are available for a particular API? A: http://api-python-client-doc.appspot.com/ has dynamically generated documentation for all the APIs supported by this library. google-api-python-client-1.2/uritemplate/0000750017135500116100000000000012200467672021460 5ustar jcgregorioeng00000000000000google-api-python-client-1.2/uritemplate/__init__.py0000640017135500116100000001125412173557443023602 0ustar jcgregorioeng00000000000000# Early, and incomplete implementation of -04. # import re import urllib RESERVED = ":/?#[]@!$&'()*+,;=" OPERATOR = "+./;?|!@" EXPLODE = "*+" MODIFIER = ":^" TEMPLATE = re.compile(r"{(?P[\+\./;\?|!@])?(?P[^}]+)}", re.UNICODE) VAR = re.compile(r"^(?P[^=\+\*:\^]+)((?P[\+\*])|(?P[:\^]-?[0-9]+))?(=(?P.*))?$", re.UNICODE) def _tostring(varname, value, explode, operator, safe=""): if type(value) == type([]): if explode == "+": return ",".join([varname + "." + urllib.quote(x, safe) for x in value]) else: return ",".join([urllib.quote(x, safe) for x in value]) if type(value) == type({}): keys = value.keys() keys.sort() if explode == "+": return ",".join([varname + "." + urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys]) else: return ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys]) else: return urllib.quote(value, safe) def _tostring_path(varname, value, explode, operator, safe=""): joiner = operator if type(value) == type([]): if explode == "+": return joiner.join([varname + "." + urllib.quote(x, safe) for x in value]) elif explode == "*": return joiner.join([urllib.quote(x, safe) for x in value]) else: return ",".join([urllib.quote(x, safe) for x in value]) elif type(value) == type({}): keys = value.keys() keys.sort() if explode == "+": return joiner.join([varname + "." + urllib.quote(key, safe) + joiner + urllib.quote(value[key], safe) for key in keys]) elif explode == "*": return joiner.join([urllib.quote(key, safe) + joiner + urllib.quote(value[key], safe) for key in keys]) else: return ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys]) else: if value: return urllib.quote(value, safe) else: return "" def _tostring_query(varname, value, explode, operator, safe=""): joiner = operator varprefix = "" if operator == "?": joiner = "&" varprefix = varname + "=" if type(value) == type([]): if 0 == len(value): return "" if explode == "+": return joiner.join([varname + "=" + urllib.quote(x, safe) for x in value]) elif explode == "*": return joiner.join([urllib.quote(x, safe) for x in value]) else: return varprefix + ",".join([urllib.quote(x, safe) for x in value]) elif type(value) == type({}): if 0 == len(value): return "" keys = value.keys() keys.sort() if explode == "+": return joiner.join([varname + "." + urllib.quote(key, safe) + "=" + urllib.quote(value[key], safe) for key in keys]) elif explode == "*": return joiner.join([urllib.quote(key, safe) + "=" + urllib.quote(value[key], safe) for key in keys]) else: return varprefix + ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys]) else: if value: return varname + "=" + urllib.quote(value, safe) else: return varname TOSTRING = { "" : _tostring, "+": _tostring, ";": _tostring_query, "?": _tostring_query, "/": _tostring_path, ".": _tostring_path, } def expand(template, vars): def _sub(match): groupdict = match.groupdict() operator = groupdict.get('operator') if operator is None: operator = '' varlist = groupdict.get('varlist') safe = "@" if operator == '+': safe = RESERVED varspecs = varlist.split(",") varnames = [] defaults = {} for varspec in varspecs: m = VAR.search(varspec) groupdict = m.groupdict() varname = groupdict.get('varname') explode = groupdict.get('explode') partial = groupdict.get('partial') default = groupdict.get('default') if default: defaults[varname] = default varnames.append((varname, explode, partial)) retval = [] joiner = operator prefix = operator if operator == "+": prefix = "" joiner = "," if operator == "?": joiner = "&" if operator == "": joiner = "," for varname, explode, partial in varnames: if varname in vars: value = vars[varname] #if not value and (type(value) == type({}) or type(value) == type([])) and varname in defaults: if not value and value != "" and varname in defaults: value = defaults[varname] elif varname in defaults: value = defaults[varname] else: continue retval.append(TOSTRING[operator](varname, value, explode, operator, safe=safe)) if "".join(retval): return prefix + joiner.join(retval) else: return "" return TEMPLATE.sub(_sub, template) google-api-python-client-1.2/README0000640017135500116100000000140212173557442020007 0ustar jcgregorioeng00000000000000This is python client library for Google's discovery based APIs. Installation ============ To install, simply use pip or easy_install: $ pip --upgrade google-api-python-client $ easy_install --upgrade google-api-python-client See the Developers Guide for more detailed instructions and documentation: https://developers.google.com/api-client-library/python/start/get_started Third Party Libraries ===================== These libraries will be installed when you install the client library: http://code.google.com/p/httplib2 http://code.google.com/p/uri-templates Depending on your version of Python, these libraries may also be installed: http://pypi.python.org/pypi/simplejson/ For development you will also need: http://pythonpaste.org/webtest/ google-api-python-client-1.2/MANIFEST.in0000640017135500116100000000023312200461705020651 0ustar jcgregorioeng00000000000000recursive-include uritemplate *.py recursive-include apiclient *.json *.py include CHANGELOG include LICENSE include README include FAQ include setpath.sh