Skip to content

Commit 68a8cfe

Browse files
committed
Flows no longer need to be saved between uses.
Also introduces util.positional declarations. Reviewed in http://codereview.appspot.com/6441056/. Fixes issue googleapis#136.
1 parent ba5c790 commit 68a8cfe

File tree

35 files changed

+569
-624
lines changed

35 files changed

+569
-624
lines changed

apiclient/discovery.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@
5757
from apiclient.schema import Schemas
5858
from email.mime.multipart import MIMEMultipart
5959
from email.mime.nonmultipart import MIMENonMultipart
60+
from oauth2client import util
6061
from oauth2client.anyjson import simplejson
6162

6263
logger = logging.getLogger(__name__)
@@ -139,6 +140,7 @@ def key2param(key):
139140
return ''.join(result)
140141

141142

143+
@util.positional(2)
142144
def build(serviceName,
143145
version,
144146
http=None,
@@ -194,18 +196,19 @@ def build(serviceName,
194196
raise UnknownApiNameOrVersion("name: %s version: %s" % (serviceName,
195197
version))
196198
if resp.status >= 400:
197-
raise HttpError(resp, content, requested_url)
199+
raise HttpError(resp, content, uri=requested_url)
198200

199201
try:
200202
service = simplejson.loads(content)
201203
except ValueError, e:
202204
logger.error('Failed to parse as JSON: ' + content)
203205
raise InvalidJsonError()
204206

205-
return build_from_document(content, discoveryServiceUrl, http=http,
207+
return build_from_document(content, base=discoveryServiceUrl, http=http,
206208
developerKey=developerKey, model=model, requestBuilder=requestBuilder)
207209

208210

211+
@util.positional(1)
209212
def build_from_document(
210213
service,
211214
base=None,
@@ -529,7 +532,8 @@ def method(self, **kwargs):
529532
raise UnknownFileType(media_filename)
530533
if not mimeparse.best_match([media_mime_type], ','.join(accept)):
531534
raise UnacceptableMimeTypeError(media_mime_type)
532-
media_upload = MediaFileUpload(media_filename, media_mime_type)
535+
media_upload = MediaFileUpload(media_filename,
536+
mimetype=media_mime_type)
533537
elif isinstance(media_filename, MediaUpload):
534538
media_upload = media_filename
535539
else:

apiclient/errors.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
2424

2525

26+
from oauth2client import util
2627
from oauth2client.anyjson import simplejson
2728

2829

@@ -34,6 +35,7 @@ class Error(Exception):
3435
class HttpError(Error):
3536
"""HTTP data was invalid or unexpected."""
3637

38+
@util.positional(3)
3739
def __init__(self, resp, content, uri=None):
3840
self.resp = resp
3941
self.content = content
@@ -92,6 +94,7 @@ class ResumableUploadError(Error):
9294
class BatchError(HttpError):
9395
"""Error occured during batch operations."""
9496

97+
@util.positional(2)
9598
def __init__(self, reason, resp=None, content=None):
9699
self.resp = resp
97100
self.content = content
@@ -106,6 +109,7 @@ def __repr__(self):
106109
class UnexpectedMethodError(Error):
107110
"""Exception raised by RequestMockBuilder on unexpected calls."""
108111

112+
@util.positional(1)
109113
def __init__(self, methodId=None):
110114
"""Constructor for an UnexpectedMethodError."""
111115
super(UnexpectedMethodError, self).__init__(

apiclient/http.py

Lines changed: 29 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
from errors import UnexpectedBodyError
4444
from errors import UnexpectedMethodError
4545
from model import JsonModel
46+
from oauth2client import util
4647
from oauth2client.anyjson import simplejson
4748

4849

@@ -162,6 +163,7 @@ def getbytes(self, begin, end):
162163
"""
163164
raise NotImplementedError()
164165

166+
@util.positional(1)
165167
def _to_json(self, strip=None):
166168
"""Utility function for creating a JSON representation of a MediaUpload.
167169
@@ -226,6 +228,7 @@ class MediaFileUpload(MediaUpload):
226228
media_body=media).execute()
227229
"""
228230

231+
@util.positional(2)
229232
def __init__(self, filename, mimetype=None, chunksize=DEFAULT_CHUNK_SIZE, resumable=False):
230233
"""Constructor.
231234
@@ -302,13 +305,13 @@ def to_json(self):
302305
string, a JSON representation of this instance, suitable to pass to
303306
from_json().
304307
"""
305-
return self._to_json(['_fd'])
308+
return self._to_json(strip=['_fd'])
306309

307310
@staticmethod
308311
def from_json(s):
309312
d = simplejson.loads(s)
310-
return MediaFileUpload(
311-
d['_filename'], d['_mimetype'], d['_chunksize'], d['_resumable'])
313+
return MediaFileUpload(d['_filename'], mimetype=d['_mimetype'],
314+
chunksize=d['_chunksize'], resumable=d['_resumable'])
312315

313316

314317
class MediaIoBaseUpload(MediaUpload):
@@ -326,6 +329,7 @@ class MediaIoBaseUpload(MediaUpload):
326329
media_body=media).execute()
327330
"""
328331

332+
@util.positional(3)
329333
def __init__(self, fd, mimetype, chunksize=DEFAULT_CHUNK_SIZE,
330334
resumable=False):
331335
"""Constructor.
@@ -414,6 +418,7 @@ class MediaInMemoryUpload(MediaUpload):
414418
method.
415419
"""
416420

421+
@util.positional(2)
417422
def __init__(self, body, mimetype='application/octet-stream',
418423
chunksize=DEFAULT_CHUNK_SIZE, resumable=False):
419424
"""Create a new MediaBytesUpload.
@@ -496,8 +501,9 @@ def to_json(self):
496501
def from_json(s):
497502
d = simplejson.loads(s)
498503
return MediaInMemoryUpload(base64.b64decode(d['_b64body']),
499-
d['_mimetype'], d['_chunksize'],
500-
d['_resumable'])
504+
mimetype=d['_mimetype'],
505+
chunksize=d['_chunksize'],
506+
resumable=d['_resumable'])
501507

502508

503509
class MediaIoBaseDownload(object):
@@ -520,6 +526,7 @@ class MediaIoBaseDownload(object):
520526
print "Download Complete!"
521527
"""
522528

529+
@util.positional(3)
523530
def __init__(self, fd, request, chunksize=DEFAULT_CHUNK_SIZE):
524531
"""Constructor.
525532
@@ -574,12 +581,13 @@ def next_chunk(self):
574581
self._done = True
575582
return MediaDownloadProgress(self._progress, self._total_size), self._done
576583
else:
577-
raise HttpError(resp, content, self._uri)
584+
raise HttpError(resp, content, uri=self._uri)
578585

579586

580587
class HttpRequest(object):
581588
"""Encapsulates a single HTTP request."""
582589

590+
@util.positional(4)
583591
def __init__(self, http, postproc, uri,
584592
method='GET',
585593
body=None,
@@ -623,6 +631,7 @@ def __init__(self, http, postproc, uri,
623631
# The bytes that have been uploaded.
624632
self.resumable_progress = 0
625633

634+
@util.positional(1)
626635
def execute(self, http=None):
627636
"""Execute the request.
628637
@@ -643,7 +652,7 @@ def execute(self, http=None):
643652
if self.resumable:
644653
body = None
645654
while body is None:
646-
_, body = self.next_chunk(http)
655+
_, body = self.next_chunk(http=http)
647656
return body
648657
else:
649658
if 'content-length' not in self.headers:
@@ -661,13 +670,14 @@ def execute(self, http=None):
661670
self.body = parsed.query
662671
self.headers['content-length'] = str(len(self.body))
663672

664-
resp, content = http.request(self.uri, self.method,
673+
resp, content = http.request(self.uri, method=self.method,
665674
body=self.body,
666675
headers=self.headers)
667676
if resp.status >= 300:
668-
raise HttpError(resp, content, self.uri)
677+
raise HttpError(resp, content, uri=self.uri)
669678
return self.postproc(resp, content)
670679

680+
@util.positional(1)
671681
def next_chunk(self, http=None):
672682
"""Execute the next step of a resumable upload.
673683
@@ -782,7 +792,7 @@ def _process_response(self, resp, content):
782792
self.resumable_uri = resp['location']
783793
else:
784794
self._in_error_state = True
785-
raise HttpError(resp, content, self.uri)
795+
raise HttpError(resp, content, uri=self.uri)
786796

787797
return (MediaUploadProgress(self.resumable_progress, self.resumable.size()),
788798
None)
@@ -844,9 +854,10 @@ def list_farmers(request_id, response, exception):
844854
845855
batch.add(service.animals().list(), list_animals)
846856
batch.add(service.farmers().list(), list_farmers)
847-
batch.execute(http)
857+
batch.execute(http=http)
848858
"""
849859

860+
@util.positional(1)
850861
def __init__(self, callback=None, batch_uri=None):
851862
"""Constructor for a BatchHttpRequest.
852863
@@ -1042,6 +1053,7 @@ def _new_id(self):
10421053
self._last_auto_id += 1
10431054
return str(self._last_auto_id)
10441055

1056+
@util.positional(2)
10451057
def add(self, request, callback=None, request_id=None):
10461058
"""Add a new request.
10471059
@@ -1119,7 +1131,7 @@ def _execute(self, http, order, requests):
11191131
headers=headers)
11201132

11211133
if resp.status >= 300:
1122-
raise HttpError(resp, content, self._batch_uri)
1134+
raise HttpError(resp, content, uri=self._batch_uri)
11231135

11241136
# Now break out the individual responses and store each one.
11251137
boundary, _ = content.split(None, 1)
@@ -1133,14 +1145,15 @@ def _execute(self, http, order, requests):
11331145
mime_response = parser.close()
11341146

11351147
if not mime_response.is_multipart():
1136-
raise BatchError("Response not in multipart/mixed format.", resp,
1137-
content)
1148+
raise BatchError("Response not in multipart/mixed format.", resp=resp,
1149+
content=content)
11381150

11391151
for part in mime_response.get_payload():
11401152
request_id = self._header_to_id(part['Content-ID'])
11411153
response, content = self._deserialize_response(part.get_payload())
11421154
self._responses[request_id] = (response, content)
11431155

1156+
@util.positional(1)
11441157
def execute(self, http=None):
11451158
"""Execute all the requests as a single batched HTTP request.
11461159
@@ -1200,7 +1213,7 @@ def execute(self, http=None):
12001213
exception = None
12011214
try:
12021215
if resp.status >= 300:
1203-
raise HttpError(resp, content, request.uri)
1216+
raise HttpError(resp, content, uri=request.uri)
12041217
response = request.postproc(resp, content)
12051218
except HttpError, e:
12061219
exception = e
@@ -1310,7 +1323,7 @@ def __call__(self, http, postproc, uri, method='GET', body=None,
13101323
raise UnexpectedBodyError(expected_body, body)
13111324
return HttpRequestMock(resp, content, postproc)
13121325
elif self.check_unexpected:
1313-
raise UnexpectedMethodError(methodId)
1326+
raise UnexpectedMethodError(methodId=methodId)
13141327
else:
13151328
model = JsonModel(False)
13161329
return HttpRequestMock(None, '{}', model.response)

apiclient/schema.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,8 @@
6262
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
6363

6464
import copy
65+
66+
from oauth2client import util
6567
from oauth2client.anyjson import simplejson
6668

6769

@@ -80,6 +82,7 @@ def __init__(self, discovery):
8082
# Cache of pretty printed schemas.
8183
self.pretty = {}
8284

85+
@util.positional(2)
8386
def _prettyPrintByName(self, name, seen=None, dent=0):
8487
"""Get pretty printed object prototype from the schema name.
8588
@@ -102,7 +105,7 @@ def _prettyPrintByName(self, name, seen=None, dent=0):
102105

103106
if name not in self.pretty:
104107
self.pretty[name] = _SchemaToStruct(self.schemas[name],
105-
seen, dent).to_str(self._prettyPrintByName)
108+
seen, dent=dent).to_str(self._prettyPrintByName)
106109

107110
seen.pop()
108111

@@ -121,6 +124,7 @@ def prettyPrintByName(self, name):
121124
# Return with trailing comma and newline removed.
122125
return self._prettyPrintByName(name, seen=[], dent=1)[:-2]
123126

127+
@util.positional(2)
124128
def _prettyPrintSchema(self, schema, seen=None, dent=0):
125129
"""Get pretty printed object prototype of schema.
126130
@@ -136,7 +140,7 @@ def _prettyPrintSchema(self, schema, seen=None, dent=0):
136140
if seen is None:
137141
seen = []
138142

139-
return _SchemaToStruct(schema, seen, dent).to_str(self._prettyPrintByName)
143+
return _SchemaToStruct(schema, seen, dent=dent).to_str(self._prettyPrintByName)
140144

141145
def prettyPrintSchema(self, schema):
142146
"""Get pretty printed object prototype of schema.
@@ -163,6 +167,7 @@ def get(self, name):
163167
class _SchemaToStruct(object):
164168
"""Convert schema to a prototype object."""
165169

170+
@util.positional(3)
166171
def __init__(self, schema, seen, dent=0):
167172
"""Constructor.
168173
@@ -256,7 +261,7 @@ def _to_str_impl(self, schema):
256261
elif '$ref' in schema:
257262
schemaName = schema['$ref']
258263
description = schema.get('description', '')
259-
s = self.from_cache(schemaName, self.seen)
264+
s = self.from_cache(schemaName, seen=self.seen)
260265
parts = s.splitlines()
261266
self.emitEnd(parts[0], description)
262267
for line in parts[1:]:

0 commit comments

Comments
 (0)