@@ -44,22 +44,33 @@ def __init__(self,
4444 self .credentials = credentials
4545
4646 def authenticate (self ):
47+ '''Establish Google credentials. This will load stored credentials
48+ and validate them, and it will call self.login() if stored
49+ credentials are unavailable or fail to validate.'''
50+
4751 self .load_credentials ()
4852
4953 if self .token is None :
5054 self .login ()
5155 else :
5256 try :
57+ # Always refresh the token. This is a dirty hack to avoid
58+ # doing anything more complicated.
5359 self .refresh ()
5460 self .validate ()
5561 except ValueError :
5662 self .login ()
5763
64+ # Add an Authorization header to all requests made through
65+ # our requests.Session object.
5866 self .session .headers .update ({
5967 'Authorization' : 'Bearer %(access_token)s' % self .token
6068 })
6169
6270 def refresh (self ):
71+ '''Use a refresh_token to refresh the access_token. See
72+ https://developers.google.com/drive/about-auth'''
73+
6374 if not 'refresh_token' in self .token :
6475 raise ValueError ('no refresh token' )
6576
@@ -76,6 +87,8 @@ def refresh(self):
7687 self .store_credentials ()
7788
7889 def login (self ):
90+ '''Perform OAuth authentication.'''
91+
7992 params = {
8093 'client_id' : self .client_id ,
8194 'scope' : ' ' .join (OAUTH_SCOPES ),
@@ -108,35 +121,48 @@ def login(self):
108121 self .store_credentials ()
109122
110123 def store_credentials (self ):
124+ '''Write credentials to file.'''
111125 with open (self .credentials , 'w' ) as fd :
112126 fd .write (yaml .safe_dump (self .token , encoding = 'utf-8' ,
113127 default_flow_style = False ))
114128
115129 def load_credentials (self ):
130+ '''Read credentials from file.'''
116131 try :
117132 with open (self .credentials ) as fd :
118133 self .token = yaml .load (fd )
119134 except IOError :
120135 pass
121136
122137 def validate (self ):
138+ '''Validate token.'''
139+
123140 r = requests .get ('%s?access_token=%s' % (
124141 VALIDATE_URI , self .token ['access_token' ]
125142 ))
126143
144+ self ._validate_response = r
145+
127146 if not r :
128147 raise ValueError ('failed to validate' )
129148
130149 def files (self ):
150+ '''Return an iterator over the files in Google Drive.'''
151+
131152 r = self .session .get ('%s/files' % DRIVE_URI ).json
132153
133154 for fspec in r ['items' ]:
134155 yield fspec
135156
136157 def get_file_metadata (self , fid ):
158+ '''Return the file metadata for a file identified by its ID.'''
159+
137160 return self .session .get ('%s/files/%s' % (DRIVE_URI , fid )).json
138161
139162 def revisions (self , fid ):
163+ '''Return an iterator over the revisions of a file
164+ identified by its ID.'''
165+
140166 r = self .session .get ('%s/files/%s/revisions' % (
141167 DRIVE_URI , fid )).json
142168
0 commit comments