From fffa7d74f610637b2a213739f664826b55a904f6 Mon Sep 17 00:00:00 2001 From: Joe Gregorio Date: Fri, 18 Feb 2011 17:20:39 -0500 Subject: [PATCH] Finish adding Storage to the OAuth 1.0 client and updated all examples to use file.Storage. No more three_legged_dance.py files anywhere. --- apiclient/ext/authtools.py | 20 +++- apiclient/ext/file.py | 2 +- docs/apiclient.anyjson.html | 2 +- docs/apiclient.contrib.html | 2 +- docs/apiclient.discovery.html | 4 +- docs/apiclient.errors.html | 2 +- docs/apiclient.ext.appengine.html | 2 +- docs/apiclient.ext.authtools.html | 15 ++- docs/apiclient.ext.django_orm.html | 2 +- docs/apiclient.ext.file.html | 89 +++++++++++++++ docs/apiclient.ext.html | 5 +- docs/apiclient.html | 13 +-- docs/apiclient.http.html | 2 +- docs/apiclient.model.html | 2 +- docs/apiclient.oauth.html | 114 ++++++++++++++++++- docs/oauth2client.appengine.html | 2 +- docs/oauth2client.client.html | 4 +- docs/oauth2client.django_orm.html | 2 +- docs/oauth2client.file.html | 2 +- docs/oauth2client.html | 2 +- docs/oauth2client.tools.html | 14 ++- oauth2client/tools.py | 15 ++- samples/buzz/buzz.py | 6 +- samples/latitude/latitude.py | 5 +- samples/localdiscovery/buzz.py | 68 +++++------ samples/localdiscovery/three_legged_dance.py | 40 ------- samples/moderator/moderator.py | 89 +++++++++------ samples/moderator/three_legged_dance.py | 41 ------- samples/threadqueue/main.py | 64 +++++++---- samples/threadqueue/three_legged_dance.py | 41 ------- 30 files changed, 410 insertions(+), 261 deletions(-) create mode 100644 docs/apiclient.ext.file.html delete mode 100644 samples/localdiscovery/three_legged_dance.py delete mode 100644 samples/moderator/three_legged_dance.py delete mode 100644 samples/threadqueue/three_legged_dance.py diff --git a/apiclient/ext/authtools.py b/apiclient/ext/authtools.py index f605d72..c383811 100644 --- a/apiclient/ext/authtools.py +++ b/apiclient/ext/authtools.py @@ -76,12 +76,21 @@ class ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler): pass -def run(flow, filename): +def run(flow, storage): """Core code for a command-line application. + + Args: + flow: Flow, an OAuth 1.0 Flow to step through. + storage: Storage, a Storage to store the credential in. + + Returns: + Credentials, the obtained credential. + + Exceptions: + RequestError: if step2 of the flow fails. + Args: """ parser = OptionParser() - parser.add_option("-f", "--file", dest="filename", - default=filename, help="write credentials to FILE", metavar="FILE") parser.add_option("-p", "--no_local_web_server", dest="localhost", action="store_false", default=True, @@ -134,9 +143,8 @@ def run(flow, filename): except RequestError: sys.exit('The authentication has failed.') - f = open(filename, 'w') - f.write(pickle.dumps(credentials)) - f.close() + storage.put(credentials) + credentials.set_store(storage.put) print "You have successfully authenticated." return credentials diff --git a/apiclient/ext/file.py b/apiclient/ext/file.py index 0a2c97c..dba723e 100644 --- a/apiclient/ext/file.py +++ b/apiclient/ext/file.py @@ -28,9 +28,9 @@ class Storage(BaseStorage): f = open(self._filename, 'r') credentials = pickle.loads(f.read()) f.close() + credentials.set_store(self.put) except: credentials = None - credentials.set_store(self.put) return credentials diff --git a/docs/apiclient.anyjson.html b/docs/apiclient.anyjson.html index df64fcd..7471a08 100644 --- a/docs/apiclient.anyjson.html +++ b/docs/apiclient.anyjson.html @@ -8,7 +8,7 @@  
 
apiclient.anyjson
index
/usr/local/google/home/jcgregorio/projects/apiclient/apiclient/anyjson.py
+>index
/home/jcgregorio/projects/apiary/apiclient/anyjson.py

Utility module to import a JSON module
 
Hides all the messy details of exactly where
diff --git a/docs/apiclient.contrib.html b/docs/apiclient.contrib.html index 488fdaa..7ac2858 100644 --- a/docs/apiclient.contrib.html +++ b/docs/apiclient.contrib.html @@ -8,7 +8,7 @@  
 
apiclient.contrib
index
/usr/local/google/home/jcgregorio/projects/apiclient/apiclient/contrib/__init__.py
+>index
/home/jcgregorio/projects/apiary/apiclient/contrib/__init__.py

diff --git a/docs/apiclient.discovery.html b/docs/apiclient.discovery.html index a192d16..f92de50 100644 --- a/docs/apiclient.discovery.html +++ b/docs/apiclient.discovery.html @@ -8,7 +8,7 @@
 
 
apiclient.discovery
index
/usr/local/google/home/jcgregorio/projects/apiclient/apiclient/discovery.py
+>index
/home/jcgregorio/projects/apiary/apiclient/discovery.py

Client for discovery based APIs
 
A client library for Google's discovery based APIs.

@@ -34,7 +34,7 @@ A client library for Google's discovery based  Functions         -
build(serviceName, version, http=None, discoveryServiceUrl='https://www.googleapis.com/discovery/v0.2beta1/describe/{api}/{apiVersion}', developerKey=None, model=<apiclient.model.JsonModel object>, requestBuilder=<class 'apiclient.http.HttpRequest'>)
Construct a Resource for interacting with an API.
+
build(serviceName, version, http=None, discoveryServiceUrl='https://www.googleapis.com/discovery/v0.3/describe/{api}/{apiVersion}', developerKey=None, model=<apiclient.model.JsonModel object>, requestBuilder=<class 'apiclient.http.HttpRequest'>)
Construct a Resource for interacting with an API.
 
Construct a Resource object for interacting with
an API. The serviceName and version are the
diff --git a/docs/apiclient.errors.html b/docs/apiclient.errors.html index 037040f..f439bc0 100644 --- a/docs/apiclient.errors.html +++ b/docs/apiclient.errors.html @@ -8,7 +8,7 @@  
 
apiclient.errors
index
/usr/local/google/home/jcgregorio/projects/apiclient/apiclient/errors.py
+>index
/home/jcgregorio/projects/apiary/apiclient/errors.py

Errors for the library.
 
All exceptions defined by the library
diff --git a/docs/apiclient.ext.appengine.html b/docs/apiclient.ext.appengine.html index b5aafca..6604c00 100644 --- a/docs/apiclient.ext.appengine.html +++ b/docs/apiclient.ext.appengine.html @@ -8,7 +8,7 @@  
 
apiclient.ext.appengine
index
/usr/local/google/home/jcgregorio/projects/apiclient/apiclient/ext/appengine.py
+>index
/home/jcgregorio/projects/apiary/apiclient/ext/appengine.py

Utilities for Google App Engine
 
Utilities for making it easier to use the
diff --git a/docs/apiclient.ext.authtools.html b/docs/apiclient.ext.authtools.html index df9e16d..0f9c083 100644 --- a/docs/apiclient.ext.authtools.html +++ b/docs/apiclient.ext.authtools.html @@ -8,7 +8,7 @@  
 
apiclient.ext.authtools
index
/usr/local/google/home/jcgregorio/projects/apiclient/apiclient/ext/authtools.py
+>index
/home/jcgregorio/projects/apiary/apiclient/ext/authtools.py

Command-line tools for authenticating via OAuth 1.0
 
Do the OAuth 1.0 Three Legged Dance for
@@ -34,7 +34,18 @@ other example apps in the same directory.

Functions         -
run(flow, filename)
Core code for a command-line application.
+
run(flow, storage)
Core code for a command-line application.

+Args:
+  flow: Flow, an OAuth 1.0 Flow to step through.
+  storage: Storage, a Storage to store the credential in.

+Returns:
+  Credentials, the obtained credential.

+Exceptions:
+  RequestError: if step2 of the flow fails.
+Args:

diff --git a/docs/apiclient.ext.django_orm.html b/docs/apiclient.ext.django_orm.html index 163f80e..73e8bea 100644 --- a/docs/apiclient.ext.django_orm.html +++ b/docs/apiclient.ext.django_orm.html @@ -8,7 +8,7 @@
 
 
apiclient.ext.django_orm
index
/usr/local/google/home/jcgregorio/projects/apiclient/apiclient/ext/django_orm.py
+>index
/home/jcgregorio/projects/apiary/apiclient/ext/django_orm.py

diff --git a/docs/apiclient.ext.file.html b/docs/apiclient.ext.file.html new file mode 100644 index 0000000..3a7ae64 --- /dev/null +++ b/docs/apiclient.ext.file.html @@ -0,0 +1,89 @@ + + +Python: module apiclient.ext.file + + +
+ +
 
+ 
apiclient.ext.file
index
/home/jcgregorio/projects/apiary/apiclient/ext/file.py
+

Utilities for OAuth.

+Utilities for making it easier to work with OAuth 1.0 credentials.

+

+ + + + + +
 
+Modules
       
pickle
+

+ + + + + +
 
+Classes
       
+
apiclient.oauth.Storage(__builtin__.object) +
+
+
Storage +
+
+
+

+ + + + + + + +
 
+class Storage(apiclient.oauth.Storage)
   Store and retrieve a single credential to and from a file.
 
 
Method resolution order:
+
Storage
+
apiclient.oauth.Storage
+
__builtin__.object
+
+
+Methods defined here:
+
__init__(self, filename)
+ +
get(self)
Retrieve Credential from file.

+Returns:
+  apiclient.oauth.Credentials
+ +
put(self, credentials)
Write a pickled Credentials to file.

+Args:
+  credentials: Credentials, the credentials to store.
+ +
+Data descriptors inherited from apiclient.oauth.Storage:
+
__dict__
+
dictionary for instance variables (if defined)
+
+
__weakref__
+
list of weak references to the object (if defined)
+
+

+ + + + + +
 
+Data
       __author__ = 'jcgregorio@google.com (Joe Gregorio)'

+ + + + + +
 
+Author
       jcgregorio@google.com (Joe Gregorio)
+ \ No newline at end of file diff --git a/docs/apiclient.ext.html b/docs/apiclient.ext.html index 5a7cfbe..d3b597d 100644 --- a/docs/apiclient.ext.html +++ b/docs/apiclient.ext.html @@ -8,7 +8,7 @@  
 
apiclient.ext
index
/usr/local/google/home/jcgregorio/projects/apiclient/apiclient/ext/__init__.py
+>index
/home/jcgregorio/projects/apiary/apiclient/ext/__init__.py

@@ -20,5 +20,6 @@
appengine
authtools
django_orm
-
+file
+ \ No newline at end of file diff --git a/docs/apiclient.html b/docs/apiclient.html index bf91ae5..4e9ce70 100644 --- a/docs/apiclient.html +++ b/docs/apiclient.html @@ -8,7 +8,7 @@  
 
apiclient
index
/usr/local/google/home/jcgregorio/projects/apiclient/apiclient/__init__.py
+>index
/home/jcgregorio/projects/apiary/apiclient/__init__.py

@@ -19,12 +19,11 @@
       
anyjson
contrib (package)
-discovery
-
errors
-ext (package)
+
discovery
+errors
+
ext (package)
http
-
json
-model
+
model
oauth
-
+ \ No newline at end of file diff --git a/docs/apiclient.http.html b/docs/apiclient.http.html index 5daef03..a9c5ce4 100644 --- a/docs/apiclient.http.html +++ b/docs/apiclient.http.html @@ -8,7 +8,7 @@  
 
apiclient.http
index
/usr/local/google/home/jcgregorio/projects/apiclient/apiclient/http.py
+>index
/home/jcgregorio/projects/apiary/apiclient/http.py

Classes to encapsulate a single HTTP request.
 
The classes implement a command pattern, with every
diff --git a/docs/apiclient.model.html b/docs/apiclient.model.html index 9a4ae1d..2a6867c 100644 --- a/docs/apiclient.model.html +++ b/docs/apiclient.model.html @@ -8,7 +8,7 @@  
 
apiclient.model
index
/usr/local/google/home/jcgregorio/projects/apiclient/apiclient/model.py
+>index
/home/jcgregorio/projects/apiary/apiclient/model.py

Model objects for requests and responses.
 
Each API may support one or more serializations, such
diff --git a/docs/apiclient.oauth.html b/docs/apiclient.oauth.html index c99f722..90be756 100644 --- a/docs/apiclient.oauth.html +++ b/docs/apiclient.oauth.html @@ -8,7 +8,7 @@  
 
apiclient.oauth
index
/usr/local/google/home/jcgregorio/projects/apiclient/apiclient/oauth.py
+>index
/home/jcgregorio/projects/apiary/apiclient/oauth.py

Utilities for OAuth.
 
Utilities for making it easier to work with OAuth.

@@ -49,7 +49,8 @@ Utilities for making it easier to work with&n
FlowThreeLegged
-
+
Storage +
exceptions.Exception(exceptions.BaseException)
@@ -57,7 +58,8 @@ Utilities for making it easier to work with&n
Error
-
MissingParameter +
CredentialsInvalidError +
MissingParameter
RequestError
@@ -95,6 +97,65 @@ Data descriptors defined here:
+ + +
 
+class CredentialsInvalidError(Error)
    
Method resolution order:
+
CredentialsInvalidError
+
Error
+
exceptions.Exception
+
exceptions.BaseException
+
__builtin__.object
+
+
+Data descriptors inherited from Error:
+
__weakref__
+
list of weak references to the object (if defined)
+
+
+Methods inherited from exceptions.Exception:
+
__init__(...)
x.__init__(...) initializes x; see x.__class__.__doc__ for signature
+ +
+Data and other attributes inherited from exceptions.Exception:
+
__new__ = <built-in method __new__ of type object>
T.__new__(S, ...) -> a new object with type S, a subtype of T
+ +
+Methods inherited from exceptions.BaseException:
+
__delattr__(...)
x.__delattr__('name') <==> del x.name
+ +
__getattribute__(...)
x.__getattribute__('name') <==> x.name
+ +
__getitem__(...)
x.__getitem__(y) <==> x[y]
+ +
__getslice__(...)
x.__getslice__(i, j) <==> x[i:j]

+Use of negative indices is not supported.
+ +
__reduce__(...)
+ +
__repr__(...)
x.__repr__() <==> repr(x)
+ +
__setattr__(...)
x.__setattr__('name', value) <==> x.name = value
+ +
__setstate__(...)
+ +
__str__(...)
x.__str__() <==> str(x)
+ +
__unicode__(...)
+ +
+Data descriptors inherited from exceptions.BaseException:
+
__dict__
+
+
args
+
+
message
+
+

+ + + @@ -292,11 +353,15 @@ Data descriptors inherited from exceptio
Methods defined here:
+
__getstate__(self)
Trim the state down to something that can be pickled.
+
__init__(self, consumer, token, user_agent)
consumer   - An instance of oauth.Consumer.
token      - An instance of oauth.Token constructed with
             the access token and secret.
user_agent - The HTTP User-Agent to provide for this application.
+
__setstate__(self, state)
Reconstitute the state of the object from being pickled.
+
authorize(self, http)
Args:
   http - An instance of httplib2.Http
       or something that acts like it.
@@ -317,6 +382,19 @@ needed for signing. So instead we have to&nbs Authorization header and then calls the original version
of 'request()'.
+
set_store(self, store)
Set the storage for the credential.

+Args:
+  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 been revoked.
+ +
+Data descriptors defined here:
+
invalid
+
True if the credentials are invalid, such as being revoked.
+

Data descriptors inherited from Credentials:
__dict__
@@ -386,6 +464,36 @@ Data descriptors inherited from exceptio
message
+
 
class Error(exceptions.Exception)
   

+ + + + + + + +
 
+class Storage(__builtin__.object)
   Base class for all Storage objects.

+Store and retrieve a single credential.
 
 Methods defined here:
+
get(self)
Retrieve credential.

+Returns:
+  apiclient.oauth.Credentials
+ +
put(self, credentials)
Write a credential.

+Args:
+  credentials: Credentials, the credentials to store.
+ +
+Data descriptors defined here:
+
__dict__
+
dictionary for instance variables (if defined)
+
+
__weakref__
+
list of weak references to the object (if defined)
+

diff --git a/docs/oauth2client.appengine.html b/docs/oauth2client.appengine.html index 4a491ad..8247e2f 100644 --- a/docs/oauth2client.appengine.html +++ b/docs/oauth2client.appengine.html @@ -8,7 +8,7 @@
 
 
oauth2client.appengine
index
/usr/local/google/home/jcgregorio/projects/apiclient/oauth2client/appengine.py
+>
index
/home/jcgregorio/projects/apiary/oauth2client/appengine.py

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

diff --git a/docs/oauth2client.client.html b/docs/oauth2client.client.html index 36bc502..431b96a 100644 --- a/docs/oauth2client.client.html +++ b/docs/oauth2client.client.html @@ -8,7 +8,7 @@  
 
oauth2client.client
index
/usr/local/google/home/jcgregorio/projects/apiclient/oauth2client/client.py
+>index
/home/jcgregorio/projects/apiary/oauth2client/client.py

An OAuth 2.0 client
 
Tools for interacting with OAuth 2.0 protected
@@ -88,7 +88,7 @@ client or another web application, and wish t only the access_token is present it can not be refreshed and will in time
expire.
 
-OAuth2Credentials objects may be safely pickled and unpickled.
+AccessTokenCredentials objects may be safely pickled and unpickled.
 
Usage:
  credentials = AccessTokenCredentials('<an access token>',
diff --git a/docs/oauth2client.django_orm.html b/docs/oauth2client.django_orm.html index 437b1c8..b9d1e03 100644 --- a/docs/oauth2client.django_orm.html +++ b/docs/oauth2client.django_orm.html @@ -8,7 +8,7 @@  
 
oauth2client.django_orm
index
/usr/local/google/home/jcgregorio/projects/apiclient/oauth2client/django_orm.py
+>index
/home/jcgregorio/projects/apiary/oauth2client/django_orm.py

OAuth 2.0 utilities for Django.
 
Utilities for using OAuth 2.0 in conjunction with
diff --git a/docs/oauth2client.file.html b/docs/oauth2client.file.html index 003db2a..e5c441f 100644 --- a/docs/oauth2client.file.html +++ b/docs/oauth2client.file.html @@ -8,7 +8,7 @@  
 
oauth2client.file
index
/usr/local/google/home/jcgregorio/projects/apiclient/oauth2client/file.py
+>index
/home/jcgregorio/projects/apiary/oauth2client/file.py

Utilities for OAuth.
 
Utilities for making it easier to work with OAuth 2.0
diff --git a/docs/oauth2client.html b/docs/oauth2client.html index 9ca5fd4..a8f23e0 100644 --- a/docs/oauth2client.html +++ b/docs/oauth2client.html @@ -8,7 +8,7 @@  
 
oauth2client
index
/usr/local/google/home/jcgregorio/projects/apiclient/oauth2client/__init__.py
+>index
/home/jcgregorio/projects/apiary/oauth2client/__init__.py

diff --git a/docs/oauth2client.tools.html b/docs/oauth2client.tools.html index 84fb49d..50e66a7 100644 --- a/docs/oauth2client.tools.html +++ b/docs/oauth2client.tools.html @@ -8,7 +8,7 @@
 
 
oauth2client.tools
index
/usr/local/google/home/jcgregorio/projects/apiclient/oauth2client/tools.py
+>index
/home/jcgregorio/projects/apiary/oauth2client/tools.py

Command-line tools for authenticating via OAuth 2.0
 
Do the OAuth 2.0 Web Server dance for a command line application. Stores the
@@ -21,7 +21,17 @@ the same directory.

Functions         -
run(flow, storage)
Core code for a command-line application.
+
run(flow, storage)
Core code for a command-line application.

+Args:
+  flow: Flow, an OAuth 2.0 Flow to step through.
+  storage: Storage, a Storage to store the credential in.

+Returns:
+  Credentials, the obtained credential.

+Exceptions:
+  RequestError: if step2 of the flow fails.

diff --git a/oauth2client/tools.py b/oauth2client/tools.py index edc8827..bd22416 100644 --- a/oauth2client/tools.py +++ b/oauth2client/tools.py @@ -25,6 +25,16 @@ __all__ = ['run'] def run(flow, storage): """Core code for a command-line application. + + Args: + flow: Flow, an OAuth 2.0 Flow to step through. + storage: Storage, a Storage to store the credential in. + + Returns: + Credentials, the obtained credential. + + Exceptions: + RequestError: if step2 of the flow fails. """ authorize_url = flow.step1_get_authorize_url('oob') @@ -37,7 +47,10 @@ def run(flow, storage): accepted = raw_input('Have you authorized me? (y/n) ') code = raw_input('What is the verification code? ').strip() - credentials = flow.step2_exchange(code) + try: + credentials = flow.step2_exchange(code) + except RequestError: + sys.exit('The authentication has failed.') storage.put(credentials) credentials.set_store(storage.put) diff --git a/samples/buzz/buzz.py b/samples/buzz/buzz.py index cf3581b..769057e 100644 --- a/samples/buzz/buzz.py +++ b/samples/buzz/buzz.py @@ -18,7 +18,6 @@ from apiclient.ext.file import Storage from apiclient.oauth import CredentialsInvalidError import httplib2 -import pickle import pprint # Uncomment the next line to get very detailed logging @@ -26,7 +25,8 @@ import pprint def main(): - credentials = Storage('buzz.dat').get() + storage = Storage('buzz.dat') + credentials = storage.get() if credentials is None or credentials.invalid == True: buzz_discovery = build("buzz", "v1").auth_discovery() @@ -38,7 +38,7 @@ def main(): scope='https://www.googleapis.com/auth/buzz', xoauth_displayname='Google API Client Example App') - credentials = run(flow, 'buzz.dat') + credentials = run(flow, storage) http = httplib2.Http() http = credentials.authorize(http) diff --git a/samples/latitude/latitude.py b/samples/latitude/latitude.py index c2ec635..4ff5b03 100644 --- a/samples/latitude/latitude.py +++ b/samples/latitude/latitude.py @@ -27,7 +27,8 @@ from apiclient.ext.file import Storage def main(): - credentials = Storage('latitude.dat').get() + storage = Storage('latitude.dat') + credentials = storage.get() if credentials is None or credentials.invalid == True: auth_discovery = build("latitude", "v1").auth_discovery() flow = FlowThreeLegged(auth_discovery, @@ -45,7 +46,7 @@ def main(): granularity='city' ) - credentials = run(flow, 'latitude.dat') + credentials = run(flow, storage) http = httplib2.Http() http = credentials.authorize(http) diff --git a/samples/localdiscovery/buzz.py b/samples/localdiscovery/buzz.py index 416f58c..8b797f7 100644 --- a/samples/localdiscovery/buzz.py +++ b/samples/localdiscovery/buzz.py @@ -11,10 +11,14 @@ latest content and then adds a new entry. __author__ = 'jcgregorio@google.com (Joe Gregorio)' +from apiclient.discovery import build from apiclient.discovery import build_from_document +from apiclient.oauth import FlowThreeLegged +from apiclient.ext.authtools import run +from apiclient.ext.file import Storage +from apiclient.oauth import CredentialsInvalidError import httplib2 -import pickle import pprint # Uncomment the next line to get very detailed logging @@ -22,10 +26,20 @@ import pprint def main(): - # Load the credentials and authorize - f = open("buzz.dat", "r") - credentials = pickle.loads(f.read()) - f.close() + storage = Storage('buzz.dat') + credentials = storage.get() + if credentials is None or credentials.invalid == True: + buzz_discovery = build("buzz", "v1").auth_discovery() + + flow = FlowThreeLegged(buzz_discovery, + consumer_key='anonymous', + consumer_secret='anonymous', + user_agent='python-buzz-sample/1.0', + domain='anonymous', + scope='https://www.googleapis.com/auth/buzz', + xoauth_displayname='Google API Client Example App') + + credentials = run(flow, storage) http = httplib2.Http() http = credentials.authorize(http) @@ -48,43 +62,15 @@ def main(): developerKey="AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0") activities = p.activities() - # Retrieve the first two activities - activitylist = activities.list( - max_results='2', scope='@self', userId='@me').execute() - print "Retrieved the first two activities" + try: + # Retrieve the first two activities + activitylist = activities.list( + max_results='2', scope='@self', userId='@me').execute() + print "Retrieved the first two activities" + except CredentialsInvalidError: + print 'Your credentials are no longer valid.' + print 'Please re-run this application to re-authorize.' - # Retrieve the next two activities - if activitylist: - activitylist = activities.list_next(activitylist).execute() - print "Retrieved the next two activities" - - # Add a new activity - new_activity_body = { - "data": { - 'title': 'Testing insert', - 'object': { - 'content': u'Just a short note to show that insert is working. ☄', - 'type': 'note'} - } - } - activity = activities.insert(userId='@me', body=new_activity_body).execute() - print "Added a new activity" - - activitylist = activities.list( - max_results='2', scope='@self', userId='@me').execute() - - # Add a comment to that activity - comment_body = { - "data": { - "content": "This is a comment" - } - } - item = activitylist['items'][0] - comment = p.comments().insert( - userId=item['actor']['id'], postId=item['id'], body=comment_body - ).execute() - print 'Added a comment to the new activity' - pprint.pprint(comment) if __name__ == '__main__': main() diff --git a/samples/localdiscovery/three_legged_dance.py b/samples/localdiscovery/three_legged_dance.py deleted file mode 100644 index 2dc26e5..0000000 --- a/samples/localdiscovery/three_legged_dance.py +++ /dev/null @@ -1,40 +0,0 @@ -# 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. - -"""Do the OAuth 1.0a three legged dance. - -Do the OAuth 1.0a three legged dance for -a Buzz command line application. Store the generated -credentials in a common file that is used by -other example apps in the same directory. -""" - -__author__ = 'jcgregorio@google.com (Joe Gregorio)' - -from apiclient.discovery import build -from apiclient.oauth import FlowThreeLegged -from apiclient.ext.authtools import run - - -buzz_discovery = build("buzz", "v1").auth_discovery() - -flow = FlowThreeLegged(buzz_discovery, - consumer_key='anonymous', - consumer_secret='anonymous', - user_agent='google-api-client-python-buzz-cmdline/1.0', - domain='anonymous', - scope='https://www.googleapis.com/auth/buzz', - xoauth_displayname='Google API Client Example App') - -run(flow, 'buzz.dat') diff --git a/samples/moderator/moderator.py b/samples/moderator/moderator.py index 89ec9ca..c22f86e 100644 --- a/samples/moderator/moderator.py +++ b/samples/moderator/moderator.py @@ -13,18 +13,33 @@ __author__ = 'jcgregorio@google.com (Joe Gregorio)' from apiclient.discovery import build +from apiclient.oauth import FlowThreeLegged +from apiclient.ext.authtools import run +from apiclient.ext.file import Storage +from apiclient.oauth import CredentialsInvalidError import httplib2 -import pickle # Uncomment to get detailed logging # httplib2.debuglevel = 4 def main(): - f = open("moderator.dat", "r") - credentials = pickle.loads(f.read()) - f.close() + storage = Storage('moderator.dat') + credentials = storage.get() + if credentials is None or credentials.invalid == True: + moderator_discovery = build("moderator", "v1").auth_discovery() + + flow = FlowThreeLegged(moderator_discovery, + consumer_key='anonymous', + consumer_secret='anonymous', + user_agent='google-api-client-python-mdrtr-cmdline/1.0', + domain='anonymous', + scope='https://www.googleapis.com/auth/moderator', + #scope='tag:google.com,2010:auth/moderator', + xoauth_displayname='Google API Client Example App') + + credentials = run(flow, storage) http = httplib2.Http() http = credentials.authorize(http) @@ -38,43 +53,47 @@ def main(): "videoSubmissionAllowed": False } } - series = p.series().insert(body=series_body).execute() - print "Created a new series" + try: + series = p.series().insert(body=series_body).execute() + print "Created a new series" - topic_body = { - "data": { - "description": "Share your ideas on eating healthy!", - "name": "Ideas", - "presenter": "liz" + topic_body = { + "data": { + "description": "Share your ideas on eating healthy!", + "name": "Ideas", + "presenter": "liz" + } } - } - topic = p.topics().insert(seriesId=series['id']['seriesId'], - body=topic_body).execute() - print "Created a new topic" + topic = p.topics().insert(seriesId=series['id']['seriesId'], + body=topic_body).execute() + print "Created a new topic" - submission_body = { - "data": { - "attachmentUrl": "http://www.youtube.com/watch?v=1a1wyc5Xxpg", - "attribution": { - "displayName": "Bashan", - "location": "Bainbridge Island, WA" - }, - "text": "Charlie Ayers @ Google" + submission_body = { + "data": { + "attachmentUrl": "http://www.youtube.com/watch?v=1a1wyc5Xxpg", + "attribution": { + "displayName": "Bashan", + "location": "Bainbridge Island, WA" + }, + "text": "Charlie Ayers @ Google" + } } - } - submission = p.submissions().insert(seriesId=topic['id']['seriesId'], - topicId=topic['id']['topicId'], body=submission_body).execute() - print "Inserted a new submisson on the topic" + submission = p.submissions().insert(seriesId=topic['id']['seriesId'], + topicId=topic['id']['topicId'], body=submission_body).execute() + print "Inserted a new submisson on the topic" - vote_body = { - "data": { - "vote": "PLUS" + vote_body = { + "data": { + "vote": "PLUS" + } } - } - p.votes().insert(seriesId=topic['id']['seriesId'], - submissionId=submission['id']['submissionId'], - body=vote_body) - print "Voted on the submission" + p.votes().insert(seriesId=topic['id']['seriesId'], + submissionId=submission['id']['submissionId'], + body=vote_body) + print "Voted on the submission" + except CredentialsInvalidError: + print 'Your credentials are no longer valid.' + print 'Please re-run this application to re-authorize.' if __name__ == '__main__': diff --git a/samples/moderator/three_legged_dance.py b/samples/moderator/three_legged_dance.py deleted file mode 100644 index 32e624d..0000000 --- a/samples/moderator/three_legged_dance.py +++ /dev/null @@ -1,41 +0,0 @@ -# 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. - -"""Do the OAuth 1.0a three legged dance. - -Do the OAuth 1.0a three legged dance for -a Buzz command line application. Store the generated -credentials in a common file that is used by -other example apps in the same directory. -""" - -__author__ = 'jcgregorio@google.com (Joe Gregorio)' - -from apiclient.discovery import build -from apiclient.oauth import FlowThreeLegged -from apiclient.ext.authtools import run - - -moderator_discovery = build("moderator", "v1").auth_discovery() - -flow = FlowThreeLegged(moderator_discovery, - consumer_key='anonymous', - consumer_secret='anonymous', - user_agent='google-api-client-python-mdrtr-cmdline/1.0', - domain='anonymous', - scope='https://www.googleapis.com/auth/moderator', - #scope='tag:google.com,2010:auth/moderator', - xoauth_displayname='Google API Client Example App') - -run(flow, 'moderator.dat') diff --git a/samples/threadqueue/main.py b/samples/threadqueue/main.py index 4e5c511..d184f6d 100644 --- a/samples/threadqueue/main.py +++ b/samples/threadqueue/main.py @@ -1,9 +1,13 @@ from apiclient.discovery import build -from apiclient.discovery import HttpError +from apiclient.discovery import build +from apiclient.errors import HttpError +from apiclient.ext.authtools import run +from apiclient.ext.file import Storage +from apiclient.oauth import CredentialsInvalidError +from apiclient.oauth import FlowThreeLegged import Queue import httplib2 -import pickle import threading import time @@ -47,8 +51,9 @@ def start_threads(credentials): def process_requests(): http = httplib2.Http() http = credentials.authorize(http) + credentials_ok = True - while True: + while credentials_ok: request = queue.get() backoff = Backoff() while backoff.loop(): @@ -59,10 +64,15 @@ def start_threads(credentials): if e.resp.status in [402, 403, 408, 503, 504]: print "Increasing backoff, got status code: %d" % e.resp.status backoff.fail() + except CredentialsInvalidError: + print "Credentials no long valid. Exiting." + credentials_ok = False + break print "Completed request" queue.task_done() + for i in range(NUM_THREADS): t = threading.Thread(target=process_requests) t.daemon = True @@ -70,9 +80,20 @@ def start_threads(credentials): def main(): - f = open("moderator.dat", "r") - credentials = pickle.loads(f.read()) - f.close() + storage = Storage('moderator.dat') + credentials = storage.get() + if credentials is None or credentials.invalid == True: + moderator_discovery = build("moderator", "v1").auth_discovery() + + flow = FlowThreeLegged(moderator_discovery, + consumer_key='anonymous', + consumer_secret='anonymous', + user_agent='google-api-client-python-thread-sample/1.0', + domain='anonymous', + scope='https://www.googleapis.com/auth/moderator', + xoauth_displayname='Google API Client Example App') + + credentials = run(flow, storage) start_threads(credentials) @@ -88,21 +109,26 @@ def main(): "videoSubmissionAllowed": False } } - series = p.series().insert(body=series_body).execute() - print "Created a new series" + try: + series = p.series().insert(body=series_body).execute() + print "Created a new series" - for i in range(NUM_ITEMS): - topic_body = { - "data": { - "description": "Sample Topic # %d" % i, - "name": "Sample", - "presenter": "me" + for i in range(NUM_ITEMS): + topic_body = { + "data": { + "description": "Sample Topic # %d" % i, + "name": "Sample", + "presenter": "me" + } } - } - topic_request = p.topics().insert(seriesId=series['id']['seriesId'], - body=topic_body) - print "Adding request to queue" - queue.put(topic_request) + topic_request = p.topics().insert(seriesId=series['id']['seriesId'], + body=topic_body) + print "Adding request to queue" + queue.put(topic_request) + except CredentialsInvalidError: + print 'Your credentials are no longer valid.' + print 'Please re-run this application to re-authorize.' + queue.join() diff --git a/samples/threadqueue/three_legged_dance.py b/samples/threadqueue/three_legged_dance.py deleted file mode 100644 index 12c495b..0000000 --- a/samples/threadqueue/three_legged_dance.py +++ /dev/null @@ -1,41 +0,0 @@ -# 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. - -"""Do the OAuth 1.0a three legged dance. - -Do the OAuth 1.0a three legged dance for -a Buzz command line application. Store the generated -credentials in a common file that is used by -other example apps in the same directory. -""" - -__author__ = 'jcgregorio@google.com (Joe Gregorio)' - -from apiclient.discovery import build -from apiclient.oauth import FlowThreeLegged -from apiclient.ext.authtools import run - - -moderator_discovery = build("moderator", "v1").auth_discovery() - -flow = FlowThreeLegged(moderator_discovery, - consumer_key='anonymous', - consumer_secret='anonymous', - user_agent='google-api-client-python-thread-sample/1.0', - domain='anonymous', - scope='https://www.googleapis.com/auth/moderator', - #scope='tag:google.com,2010:auth/moderator', - xoauth_displayname='Google API Client Example App') - -run(flow, 'moderator.dat')