Commits

Sebastian Rahlf committed 737a2bd

Ported to python 3.1.

Comments (0)

Files changed (11)

 import re
 import socket
 from time import strftime, gmtime
-from urlparse import urlsplit
-from urllib2 import quote, urlopen, HTTPError
+from urllib.parse import urlsplit
+from urllib.parse import quote
+from urllib.request import urlopen
+from urllib.error import HTTPError
 
 LOCALES = {
     'ca' : 'http://ecs.amazonaws.ca/onca/xml', 
         socket.setdefaulttimeout(self.TIMEOUT)
         
         self.last_call = datetime(1970, 1, 1)
-        self.throttle = timedelta(seconds=1)/self.REQUESTS_PER_SECOND
+        self.throttle = timedelta(seconds=1) // self.REQUESTS_PER_SECOND
         
         self.response_processor = processor
         
         http://blog.umlungu.co.uk/blog/2009/jul/12/pyaws-adding-request-authentication/)
         """
         # remove empty (=None) parameters
-        for key, val in qargs.items():
+        for key, val in list(qargs.items()):
             if val is None:
                 del qargs[key]
         
         msg = 'GET'
         msg += '\n' + self.host
         msg += '\n' + self.path
-        msg += '\n' + args.encode('utf-8')
+        msg += '\n' + args #.encode('utf-8')
         
         signature = quote(
-            b64encode(hmac.new(self.secret_key, msg, sha256).digest()))
+            b64encode(hmac.new(self.secret_key.encode('utf-8'), 
+                msg.encode('utf-8'), sha256).digest()))
         
         url = '%s://%s%s?%s&Signature=%s' % (self.scheme, self.host, self.path, 
                                              args, signature)
         
         try:
             return urlopen(url)
-        except HTTPError, e:
+        except HTTPError as e:
             if e.code == 503:
                 raise TooManyRequests
             # otherwise re-raise
             url = self._build_url(Operation='ItemLookup', ItemId=id, **params)
             fp = self._call(url)
             return self._parse(fp)
-        except AWSError, e:
+        except AWSError as e:
             
             if (e.code=='AWS.InvalidEnumeratedParameter' 
             and INVALID_VALUE_REG.search(e.msg).group('parameter')=='SearchIndex'):
                                   SearchIndex=search_index, **params)
             fp = self._call(url)
             return self._parse(fp)
-        except AWSError, e:
+        except AWSError as e:
             
             if (e.code=='AWS.InvalidEnumeratedParameter' 
             and INVALID_VALUE_REG.search(e.msg)):
                                   ItemId=item_id, **params)
             fp = self._call(url)
             return self._parse(fp)
-        except AWSError, e:
+        except AWSError as e:
             
             if e.code=='AWS.ECommerceService.NoSimilarities':
                 asin = NOSIMILARITIES_REG.search(e.msg).group('ASIN')
                                   ListType=list_type, **params)
             fp = self._call(url)
             return self._parse(fp)
-        except AWSError, e:
+        except AWSError as e:
             
             if (e.code=='AWS.InvalidEnumeratedParameter' 
             and INVALID_VALUE_REG.search(e.msg).group('parameter')=='ListType'):
                                   ListType=list_type, **params)
             fp = self._call(url)
             return self._parse(fp)
-        except AWSError, e:
+        except AWSError as e:
             
             if (e.code=='AWS.InvalidEnumeratedParameter' 
             and INVALID_VALUE_REG.search(e.msg).group('parameter')=='ListType'):
                     HelpType=help_type, ResponseGroup=response_group, **params)
             fp = self._call(url)
             return self._parse(fp)
-        except AWSError, e:
+        except AWSError as e:
             
             m = INVALID_VALUE_REG.search(e.msg)
             if e.code=='AWS.InvalidEnumeratedParameter': 
                     **params)
             fp = self._call(url)
             return self._parse(fp)
-        except AWSError, e:
+        except AWSError as e:
             
             if e.code=='AWS.InvalidResponseGroup': 
                 raise InvalidResponseGroup(params.get('ResponseGroup'))
             return root.xpath(self.total_pages_xpath, 
                           namespaces={'aws' : self.nspace})[0].pyval
         except IndexError:
-            return None
+            return 0
         
     def _get_current_page_numer(self, root):
         """
             return root.xpath(self.current_page_xpath, 
                           namespaces={'aws' : self.nspace})[0].pyval
         except IndexError:
-            return None
+            return 0
     
     def _get_total_results(self, root):
         """
             return root.xpath(self.total_results_xpath, 
                           namespaces={'aws' : self.nspace})
         except IndexError:
-            return None
+            return 0
 
 master_doc = 'index'
 
 # General information about the project.
-project = u'python-amazon-product-api'
+project = 'python-amazon-product-api'
 copyright = '%s, Sebastian Rahlf' % '-'.join(set(['2009', time.strftime('%Y')]))
 
 # The version info for the project you're documenting, acts as replacement for
 # (source start file, target name, title, author, document class [howto/manual]).
 latex_documents = [
   ('index', 'python-amazon-product-api.tex', 
-   ur'python-amazon-product-api Documentation',
-   ur'Sebastian Rahlf', 'manual'),
+   r'python-amazon-product-api Documentation',
+   r'Sebastian Rahlf', 'manual'),
 ]
 
 # The name of an image file (relative to this directory) to place at the top of

examples/all-galileo-titles.py

         except AttributeError:
             current_page = 1
             
-        print 'page %d of %d' % (current_page, total_pages)
+        print('page %d of %d' % (current_page, total_pages))
         
         #~ from lxml import etree
         #~ print etree.tostring(root, pretty_print=True)
                              namespaces={'aws' : nspace})
         
         for book in books:
-            print book.ASIN,
-            print unicode(book.ItemAttributes.Author), ':', 
-            print unicode(book.ItemAttributes.Title)
+            print(book.ASIN, end=' ')
+            print(str(book.ItemAttributes.Author), ':', end=' ') 
+            print(str(book.ItemAttributes.Title))
             

examples/get-cover.py

 from optparse import OptionParser
 import os.path
 import sys
-import urllib2
+import urllib.request, urllib.error, urllib.parse
 
 from config import AWS_KEY, SECRET_KEY
 from amazonproduct import API
     Downloads image and saves it to ``dest_path``.
     """
     fp = open(dest_path, 'wb')
-    fp.write(urllib2.urlopen(url).read())
+    fp.write(urllib.request.urlopen(url).read())
     fp.close()
 
 if __name__ == '__main__':
         
         id = id.replace('-', '')
         
-        if options.verbose: print 'Fetching info for %s...' % id
+        if options.verbose: print('Fetching info for %s...' % id)
         root = api.item_lookup(id, **params)
         
         #~ from lxml import etree
         url = root.Items.Item.LargeImage.URL.pyval
         name, ext = os.path.splitext(url)
         path = '%s%s' % (id, ext)
-        if options.verbose: print 'Downloading %s to %s ...' % (url, path)
+        if options.verbose: print('Downloading %s to %s ...' % (url, path))
         fetch_image(url, path)
         

examples/node-browser.py

         # populate with root nodes
         # but avoid duplicated node ids
         node_ids = set(NODE_IDS[self.locale].values())
-        for name, id in NODE_IDS[self.locale].items():
+        for name, id in list(NODE_IDS[self.locale].items()):
             if id in node_ids:
                 self.treestore.append(None, [id, name])
                 node_ids.remove(id)
         except AttributeError:
             children = {}
         
-        for child_id, child_name in children.items():
+        for child_id, child_name in list(children.items()):
             self.treestore.append(row.iter, [child_id, child_name])
             
         # expand nodes of just added

examples/reviews.py

 if __name__ == '__main__':
     
     if len(sys.argv[1:]) == 0:
-        print __doc__
-        print 'Usage: %s ISBN' % sys.argv[0]
+        print(__doc__)
+        print('Usage: %s ISBN' % sys.argv[0])
         sys.exit(1)
     
     for isbn in sys.argv[1:]:
             except AttributeError:
                 current_page = 1
                 
-            print '%d reviews' % total_reviews,
-            print 'requested page %d of %d' % (current_page, review_pages)
+            print('%d reviews' % total_reviews, end=' ')
+            print('requested page %d of %d' % (current_page, review_pages))
             
             nspace = root.nsmap.get(None, '')
             reviews = root.xpath('//aws:CustomerReviews/aws:Review', 
                                 namespaces={'aws' : nspace})
             for review in reviews:
-                print '%s %-5s %s: %s' % (review.Date, '*' * review.Rating.pyval,  
-                                          unicode(review.Reviewer.Name),
-                                          unicode(review.Summary))
+                print('%s %-5s %s: %s' % (review.Date, '*' * review.Rating.pyval,  
+                                          str(review.Reviewer.Name),
+                                          str(review.Summary)))

examples/similar.py

                          namespaces={'aws' : nspace})
     
     for book in books:
-        print 'ASIN %-10s' % book.ASIN,
-        print unicode(book.ItemAttributes.Author), ':', 
-        print unicode(book.ItemAttributes.Title)
+        print('ASIN %-10s' % book.ASIN, end=' ')
+        print(str(book.ItemAttributes.Author), ':', end=' ') 
+        print(str(book.ItemAttributes.Title))
         

examples/using-xml-minidom.py

               processor=minidom_response_parser)
     root = api.item_lookup('0718155157')
     
-    print root.toprettyxml()
+    print(root.toprettyxml())
     
     # ...
     # now do something with it! 

examples/wishlists.py

 if __name__ == '__main__':
     
     for list in get_wishlists(FirstName='John', LastName='Doe'):
-        print list.customer
-        print '%(name)r with %(total_items)i items' % list.__dict__
-        print 'created: %(created)s last modified: %(last_modified)s' % list.__dict__ 
-        print list.url
-        print
+        print(list.customer)
+        print('%(name)r with %(total_items)i items' % list.__dict__)
+        print('created: %(created)s last modified: %(last_modified)s' % list.__dict__) 
+        print(list.url)
+        print()
         
         for item in get_wishlist_items(list.id):
             
             number = item.number_desired - item.number_received
-            print '%3ix %s (%s)' % (number, item.title, item.asin)
+            print('%3ix %s (%s)' % (number, item.title, item.asin))
             
-        print
+        print()
     
  

tests/parser-performance.py

         for file in files
         if os.path.splitext(file)[1].lower() == '.xml']
 
-    print "Parsing %i XML files..." % (len(xml_files)*RUNS, )
-    for label, parser in custom_parsers.items():
-        print label, 
+    print("Parsing %i XML files..." % (len(xml_files)*RUNS, ))
+    for label, parser in list(custom_parsers.items()):
+        print(label, end=' ') 
         start = time.clock()
         api = API(AWS_KEY, SECRET_KEY, processor=parser)
         for i in range(RUNS):
                 except AWSError:
                     pass
         stop = time.clock()
-        print stop - start
+        print(stop - start)

tests/test-xml-responses.py

 from lxml import etree
 import os, os.path
 import re
-from StringIO import StringIO
+from io import StringIO
 import unittest
-import urllib2
+import urllib.request, urllib.error, urllib.parse
 
 _here = os.path.abspath(os.path.dirname(__file__))
 
         # Harry Potter and the Philosopher's Stone
         try:
             self.api.item_lookup('9780747532743', IdType='ISBN')
-        except AWSError, e:
+        except AWSError as e:
             self.assert_(e.code == 'AWS.MissingParameterValueCombination')
         
         
         try:
             self.assertRaises(InvalidResponseGroup, 
                               self.api.item_search, 'Books')
-        except AWSError, e:
+        except AWSError as e:
             self.assert_(e.code == 'AWS.MinimumParameterRequirement')
         
     def test_invalid_response_group(self):
         self.assertEquals(info.ValidOperations.Operation.pyval, 'Help')
         
         # check that all required elements are contained in XML
-        elements = map(lambda x: x.strip(), '''Arguments/Argument/Name
+        elements = [x.strip() for x in '''Arguments/Argument/Name
         Arguments/Argument/Value
         Errors/Error/Code
         Errors/Error/Message
         ResponseGroupInformation/CreationDate
         ResponseGroupInformation/Elements/Element
         ResponseGroupInformation/Name
-        ResponseGroupInformation/ValidOperations/Operation'''.splitlines())
+        ResponseGroupInformation/ValidOperations/Operation'''.splitlines()]
         self._check_elements(info, elements)