Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(400)

Side by Side Diff: third_party/gsutil/boto/mws/response.py

Issue 12042069: Scripts to download files from google storage based on sha1 sums (Closed) Base URL: https://chromium.googlesource.com/chromium/tools/depot_tools.git@master
Patch Set: Removed gsutil/tests and gsutil/docs Created 7 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 # Copyright (c) 2012 Andy Davidoff http://www.disruptek.com/
2 #
3 # Permission is hereby granted, free of charge, to any person obtaining a
4 # copy of this software and associated documentation files (the
5 # "Software"), to deal in the Software without restriction, including
6 # without limitation the rights to use, copy, modify, merge, publish, dis-
7 # tribute, sublicense, and/or sell copies of the Software, and to permit
8 # persons to whom the Software is furnished to do so, subject to the fol-
9 # lowing conditions:
10 #
11 # The above copyright notice and this permission notice shall be included
12 # in all copies or substantial portions of the Software.
13 #
14 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
16 # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
17 # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
18 # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
20 # IN THE SOFTWARE.
21 from decimal import Decimal
22
23
24 class ComplexType(dict):
25 _value = 'Value'
26
27 def __repr__(self):
28 return '{0}{1}'.format(getattr(self, self._value, None), self.copy())
29
30 def __str__(self):
31 return str(getattr(self, self._value, ''))
32
33
34 class DeclarativeType(object):
35 def __init__(self, _hint=None, **kw):
36 if _hint is not None:
37 self._hint = _hint
38 else:
39 class JITResponse(ResponseElement):
40 pass
41 self._hint = JITResponse
42 for name, value in kw.items():
43 setattr(self._hint, name, value)
44 self._value = None
45
46 def setup(self, parent, name, *args, **kw):
47 self._parent = parent
48 self._name = name
49 self._clone = self.__class__(self._hint)
50 self._clone._parent = parent
51 self._clone._name = name
52 setattr(self._parent, self._name, self._clone)
53
54 def start(self, *args, **kw):
55 raise NotImplemented
56
57 def end(self, *args, **kw):
58 raise NotImplemented
59
60 def teardown(self, *args, **kw):
61 if self._value is None:
62 delattr(self._parent, self._name)
63 else:
64 setattr(self._parent, self._name, self._value)
65
66
67 class Element(DeclarativeType):
68 def start(self, *args, **kw):
69 self._value = self._hint(parent=self._parent, **kw)
70 return self._value
71
72 def end(self, *args, **kw):
73 pass
74
75
76 class SimpleList(DeclarativeType):
77 def __init__(self, *args, **kw):
78 DeclarativeType.__init__(self, *args, **kw)
79 self._value = []
80
81 def teardown(self, *args, **kw):
82 if self._value == []:
83 self._value = None
84 DeclarativeType.teardown(self, *args, **kw)
85
86 def start(self, *args, **kw):
87 return None
88
89 def end(self, name, value, *args, **kw):
90 self._value.append(value)
91
92
93 class ElementList(SimpleList):
94 def start(self, *args, **kw):
95 value = self._hint(parent=self._parent, **kw)
96 self._value += [value]
97 return self._value[-1]
98
99 def end(self, *args, **kw):
100 pass
101
102
103 class MemberList(ElementList):
104 def __init__(self, *args, **kw):
105 self._this = kw.get('this')
106 ElementList.__init__(self, *args, **kw)
107
108 def start(self, attrs={}, **kw):
109 Class = self._this or self._parent._type_for(self._name, attrs)
110 if issubclass(self._hint, ResponseElement):
111 ListClass = ElementList
112 else:
113 ListClass = SimpleList
114 setattr(Class, Class._member, ListClass(self._hint))
115 self._value = Class(attrs=attrs, parent=self._parent, **kw)
116 return self._value
117
118 def end(self, *args, **kw):
119 self._value = getattr(self._value, self._value._member)
120 ElementList.end(self, *args, **kw)
121
122
123 def ResponseFactory(action):
124 result = globals().get(action + 'Result', ResponseElement)
125
126 class MWSResponse(Response):
127 _name = action + 'Response'
128
129 setattr(MWSResponse, action + 'Result', Element(result))
130 return MWSResponse
131
132
133 def strip_namespace(func):
134 def wrapper(self, name, *args, **kw):
135 if self._namespace is not None:
136 if name.startswith(self._namespace + ':'):
137 name = name[len(self._namespace + ':'):]
138 return func(self, name, *args, **kw)
139 return wrapper
140
141
142 class ResponseElement(dict):
143 _override = {}
144 _member = 'member'
145 _name = None
146 _namespace = None
147
148 def __init__(self, connection=None, name=None, parent=None, attrs={}):
149 if parent is not None and self._namespace is None:
150 self._namespace = parent._namespace
151 if connection is not None:
152 self._connection = connection
153 self._name = name or self._name or self.__class__.__name__
154 self._declared('setup', attrs=attrs)
155 dict.__init__(self, attrs.copy())
156
157 def _declared(self, op, **kw):
158 def inherit(obj):
159 result = {}
160 for cls in getattr(obj, '__bases__', ()):
161 result.update(inherit(cls))
162 result.update(obj.__dict__)
163 return result
164
165 scope = inherit(self.__class__)
166 scope.update(self.__dict__)
167 declared = lambda attr: isinstance(attr[1], DeclarativeType)
168 for name, node in filter(declared, scope.items()):
169 getattr(node, op)(self, name, parentname=self._name, **kw)
170
171 @property
172 def connection(self):
173 return self._connection
174
175 def __repr__(self):
176 render = lambda pair: '{0!s}: {1!r}'.format(*pair)
177 do_show = lambda pair: not pair[0].startswith('_')
178 attrs = filter(do_show, self.__dict__.items())
179 name = self.__class__.__name__
180 if name == 'JITResponse':
181 name = '^{0}^'.format(self._name or '')
182 elif name == 'MWSResponse':
183 name = '^{0}^'.format(self._name or name)
184 return '{0}{1!r}({2})'.format(
185 name, self.copy(), ', '.join(map(render, attrs)))
186
187 def _type_for(self, name, attrs):
188 return self._override.get(name, globals().get(name, ResponseElement))
189
190 @strip_namespace
191 def startElement(self, name, attrs, connection):
192 attribute = getattr(self, name, None)
193 if isinstance(attribute, DeclarativeType):
194 return attribute.start(name=name, attrs=attrs,
195 connection=connection)
196 elif attrs.getLength():
197 setattr(self, name, ComplexType(attrs.copy()))
198 else:
199 return None
200
201 @strip_namespace
202 def endElement(self, name, value, connection):
203 attribute = getattr(self, name, None)
204 if name == self._name:
205 self._declared('teardown')
206 elif isinstance(attribute, DeclarativeType):
207 attribute.end(name=name, value=value, connection=connection)
208 elif isinstance(attribute, ComplexType):
209 setattr(attribute, attribute._value, value)
210 else:
211 setattr(self, name, value)
212
213
214 class Response(ResponseElement):
215 ResponseMetadata = Element()
216
217 @strip_namespace
218 def startElement(self, name, attrs, connection):
219 if name == self._name:
220 self.update(attrs)
221 else:
222 return ResponseElement.startElement(self, name, attrs, connection)
223
224 @property
225 def _result(self):
226 return getattr(self, self._action + 'Result', None)
227
228 @property
229 def _action(self):
230 return (self._name or self.__class__.__name__)[:-len('Response')]
231
232
233 class ResponseResultList(Response):
234 _ResultClass = ResponseElement
235
236 def __init__(self, *args, **kw):
237 setattr(self, self._action + 'Result', ElementList(self._ResultClass))
238 Response.__init__(self, *args, **kw)
239
240
241 class FeedSubmissionInfo(ResponseElement):
242 pass
243
244
245 class SubmitFeedResult(ResponseElement):
246 FeedSubmissionInfo = Element(FeedSubmissionInfo)
247
248
249 class GetFeedSubmissionListResult(ResponseElement):
250 FeedSubmissionInfo = ElementList(FeedSubmissionInfo)
251
252
253 class GetFeedSubmissionListByNextTokenResult(GetFeedSubmissionListResult):
254 pass
255
256
257 class GetFeedSubmissionCountResult(ResponseElement):
258 pass
259
260
261 class CancelFeedSubmissionsResult(GetFeedSubmissionListResult):
262 pass
263
264
265 class GetServiceStatusResult(ResponseElement):
266 Messages = Element(Messages=ElementList())
267
268
269 class ReportRequestInfo(ResponseElement):
270 pass
271
272
273 class RequestReportResult(ResponseElement):
274 ReportRequestInfo = Element()
275
276
277 class GetReportRequestListResult(RequestReportResult):
278 ReportRequestInfo = ElementList()
279
280
281 class GetReportRequestListByNextTokenResult(GetReportRequestListResult):
282 pass
283
284
285 class CancelReportRequestsResult(RequestReportResult):
286 pass
287
288
289 class GetReportListResult(ResponseElement):
290 ReportInfo = ElementList()
291
292
293 class GetReportListByNextTokenResult(GetReportListResult):
294 pass
295
296
297 class ManageReportScheduleResult(ResponseElement):
298 ReportSchedule = Element()
299
300
301 class GetReportScheduleListResult(ManageReportScheduleResult):
302 pass
303
304
305 class GetReportScheduleListByNextTokenResult(GetReportScheduleListResult):
306 pass
307
308
309 class UpdateReportAcknowledgementsResult(GetReportListResult):
310 pass
311
312
313 class CreateInboundShipmentPlanResult(ResponseElement):
314 InboundShipmentPlans = MemberList(ShipToAddress=Element(),
315 Items=MemberList())
316
317
318 class ListInboundShipmentsResult(ResponseElement):
319 ShipmentData = MemberList(Element(ShipFromAddress=Element()))
320
321
322 class ListInboundShipmentsByNextTokenResult(ListInboundShipmentsResult):
323 pass
324
325
326 class ListInboundShipmentItemsResult(ResponseElement):
327 ItemData = MemberList()
328
329
330 class ListInboundShipmentItemsByNextTokenResult(ListInboundShipmentItemsResult):
331 pass
332
333
334 class ListInventorySupplyResult(ResponseElement):
335 InventorySupplyList = MemberList(
336 EarliestAvailability=Element(),
337 SupplyDetail=MemberList(\
338 EarliestAvailabileToPick=Element(),
339 LatestAvailableToPick=Element(),
340 )
341 )
342
343
344 class ListInventorySupplyByNextTokenResult(ListInventorySupplyResult):
345 pass
346
347
348 class ComplexAmount(ResponseElement):
349 _amount = 'Value'
350
351 def __repr__(self):
352 return '{0} {1}'.format(self.CurrencyCode, getattr(self, self._amount))
353
354 def __float__(self):
355 return float(getattr(self, self._amount))
356
357 def __str__(self):
358 return str(getattr(self, self._amount))
359
360 @strip_namespace
361 def startElement(self, name, attrs, connection):
362 if name not in ('CurrencyCode', self._amount):
363 message = 'Unrecognized tag {0} in ComplexAmount'.format(name)
364 raise AssertionError(message)
365 return ResponseElement.startElement(self, name, attrs, connection)
366
367 @strip_namespace
368 def endElement(self, name, value, connection):
369 if name == self._amount:
370 value = Decimal(value)
371 ResponseElement.endElement(self, name, value, connection)
372
373
374 class ComplexMoney(ComplexAmount):
375 _amount = 'Amount'
376
377
378 class ComplexWeight(ResponseElement):
379 def __repr__(self):
380 return '{0} {1}'.format(self.Value, self.Unit)
381
382 def __float__(self):
383 return float(self.Value)
384
385 def __str__(self):
386 return str(self.Value)
387
388 @strip_namespace
389 def startElement(self, name, attrs, connection):
390 if name not in ('Unit', 'Value'):
391 message = 'Unrecognized tag {0} in ComplexWeight'.format(name)
392 raise AssertionError(message)
393 return ResponseElement.startElement(self, name, attrs, connection)
394
395 @strip_namespace
396 def endElement(self, name, value, connection):
397 if name == 'Value':
398 value = Decimal(value)
399 ResponseElement.endElement(self, name, value, connection)
400
401
402 class Dimension(ComplexType):
403 _value = 'Value'
404
405
406 class ComplexDimensions(ResponseElement):
407 _dimensions = ('Height', 'Length', 'Width', 'Weight')
408
409 def __repr__(self):
410 values = [getattr(self, key, None) for key in self._dimensions]
411 values = filter(None, values)
412 return 'x'.join(map('{0.Value:0.2f}{0[Units]}'.format, values))
413
414 @strip_namespace
415 def startElement(self, name, attrs, connection):
416 if name not in self._dimensions:
417 message = 'Unrecognized tag {0} in ComplexDimensions'.format(name)
418 raise AssertionError(message)
419 setattr(self, name, Dimension(attrs.copy()))
420
421 @strip_namespace
422 def endElement(self, name, value, connection):
423 if name in self._dimensions:
424 value = Decimal(value or '0')
425 ResponseElement.endElement(self, name, value, connection)
426
427
428 class FulfillmentPreviewItem(ResponseElement):
429 EstimatedShippingWeight = Element(ComplexWeight)
430
431
432 class FulfillmentPreview(ResponseElement):
433 EstimatedShippingWeight = Element(ComplexWeight)
434 EstimatedFees = MemberList(\
435 Element(\
436 Amount=Element(ComplexAmount),
437 ),
438 )
439 UnfulfillablePreviewItems = MemberList(FulfillmentPreviewItem)
440 FulfillmentPreviewShipments = MemberList(\
441 FulfillmentPreviewItems=MemberList(FulfillmentPreviewItem),
442 )
443
444
445 class GetFulfillmentPreviewResult(ResponseElement):
446 FulfillmentPreviews = MemberList(FulfillmentPreview)
447
448
449 class FulfillmentOrder(ResponseElement):
450 DestinationAddress = Element()
451 NotificationEmailList = MemberList(str)
452
453
454 class GetFulfillmentOrderResult(ResponseElement):
455 FulfillmentOrder = Element(FulfillmentOrder)
456 FulfillmentShipment = MemberList(Element(\
457 FulfillmentShipmentItem=MemberList(),
458 FulfillmentShipmentPackage=MemberList(),
459 )
460 )
461 FulfillmentOrderItem = MemberList()
462
463
464 class ListAllFulfillmentOrdersResult(ResponseElement):
465 FulfillmentOrders = MemberList(FulfillmentOrder)
466
467
468 class ListAllFulfillmentOrdersByNextTokenResult(ListAllFulfillmentOrdersResult):
469 pass
470
471
472 class Image(ResponseElement):
473 pass
474
475
476 class AttributeSet(ResponseElement):
477 ItemDimensions = Element(ComplexDimensions)
478 ListPrice = Element(ComplexMoney)
479 PackageDimensions = Element(ComplexDimensions)
480 SmallImage = Element(Image)
481
482
483 class ItemAttributes(AttributeSet):
484 Languages = Element(Language=ElementList())
485
486 def __init__(self, *args, **kw):
487 names = ('Actor', 'Artist', 'Author', 'Creator', 'Director',
488 'Feature', 'Format', 'GemType', 'MaterialType',
489 'MediaType', 'OperatingSystem', 'Platform')
490 for name in names:
491 setattr(self, name, SimpleList())
492 AttributeSet.__init__(self, *args, **kw)
493
494
495 class VariationRelationship(ResponseElement):
496 Identifiers = Element(MarketplaceASIN=Element(),
497 SKUIdentifier=Element())
498 GemType = SimpleList()
499 MaterialType = SimpleList()
500 OperatingSystem = SimpleList()
501
502
503 class Price(ResponseElement):
504 LandedPrice = Element(ComplexMoney)
505 ListingPrice = Element(ComplexMoney)
506 Shipping = Element(ComplexMoney)
507
508
509 class CompetitivePrice(ResponseElement):
510 Price = Element(Price)
511
512
513 class CompetitivePriceList(ResponseElement):
514 CompetitivePrice = ElementList(CompetitivePrice)
515
516
517 class CompetitivePricing(ResponseElement):
518 CompetitivePrices = Element(CompetitivePriceList)
519 NumberOfOfferListings = SimpleList()
520 TradeInValue = Element(ComplexMoney)
521
522
523 class SalesRank(ResponseElement):
524 pass
525
526
527 class LowestOfferListing(ResponseElement):
528 Qualifiers = Element(ShippingTime=Element())
529 Price = Element(Price)
530
531
532 class Product(ResponseElement):
533 _namespace = 'ns2'
534 Identifiers = Element(MarketplaceASIN=Element(),
535 SKUIdentifier=Element())
536 AttributeSets = Element(\
537 ItemAttributes=ElementList(ItemAttributes),
538 )
539 Relationships = Element(\
540 VariationParent=ElementList(VariationRelationship),
541 )
542 CompetitivePricing = ElementList(CompetitivePricing)
543 SalesRankings = Element(\
544 SalesRank=ElementList(SalesRank),
545 )
546 LowestOfferListings = Element(\
547 LowestOfferListing=ElementList(LowestOfferListing),
548 )
549
550
551 class ListMatchingProductsResult(ResponseElement):
552 Products = Element(Product=ElementList(Product))
553
554
555 class ProductsBulkOperationResult(ResponseElement):
556 Product = Element(Product)
557 Error = Element()
558
559
560 class ProductsBulkOperationResponse(ResponseResultList):
561 _ResultClass = ProductsBulkOperationResult
562
563
564 class GetMatchingProductResponse(ProductsBulkOperationResponse):
565 pass
566
567
568 class GetMatchingProductForIdResult(ListMatchingProductsResult):
569 pass
570
571
572 class GetCompetitivePricingForSKUResponse(ProductsBulkOperationResponse):
573 pass
574
575
576 class GetCompetitivePricingForASINResponse(ProductsBulkOperationResponse):
577 pass
578
579
580 class GetLowestOfferListingsForSKUResponse(ProductsBulkOperationResponse):
581 pass
582
583
584 class GetLowestOfferListingsForASINResponse(ProductsBulkOperationResponse):
585 pass
586
587
588 class ProductCategory(ResponseElement):
589
590 def __init__(self, *args, **kw):
591 setattr(self, 'Parent', Element(ProductCategory))
592 ResponseElement.__init__(self, *args, **kw)
593
594
595 class GetProductCategoriesResult(ResponseElement):
596 Self = Element(ProductCategory)
597
598
599 class GetProductCategoriesForSKUResult(GetProductCategoriesResult):
600 pass
601
602
603 class GetProductCategoriesForASINResult(GetProductCategoriesResult):
604 pass
605
606
607 class Order(ResponseElement):
608 OrderTotal = Element(ComplexMoney)
609 ShippingAddress = Element()
610 PaymentExecutionDetail = Element(\
611 PaymentExecutionDetailItem=ElementList(\
612 PaymentExecutionDetailItem=Element(\
613 Payment=Element(ComplexMoney)
614 )
615 )
616 )
617
618
619 class ListOrdersResult(ResponseElement):
620 Orders = Element(Order=ElementList(Order))
621
622
623 class ListOrdersByNextTokenResult(ListOrdersResult):
624 pass
625
626
627 class GetOrderResult(ListOrdersResult):
628 pass
629
630
631 class OrderItem(ResponseElement):
632 ItemPrice = Element(ComplexMoney)
633 ShippingPrice = Element(ComplexMoney)
634 GiftWrapPrice = Element(ComplexMoney)
635 ItemTax = Element(ComplexMoney)
636 ShippingTax = Element(ComplexMoney)
637 GiftWrapTax = Element(ComplexMoney)
638 ShippingDiscount = Element(ComplexMoney)
639 PromotionDiscount = Element(ComplexMoney)
640 PromotionIds = SimpleList()
641 CODFee = Element(ComplexMoney)
642 CODFeeDiscount = Element(ComplexMoney)
643
644
645 class ListOrderItemsResult(ResponseElement):
646 OrderItems = Element(OrderItem=ElementList(OrderItem))
647
648
649 class ListMarketplaceParticipationsResult(ResponseElement):
650 ListParticipations = Element(Participation=ElementList())
651 ListMarketplaces = Element(Marketplace=ElementList())
652
653
654 class ListMarketplaceParticipationsByNextTokenResult(ListMarketplaceParticipatio nsResult):
655 pass
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698