| 28 | | * PyAmazon は内部で Amazon API の XML を呼び出して xml.dom.minidom で解析した後,unmarshal という関数で階層構造に沿ってオブジェクトを作っている.そのため,XML の構造がそのまま Python のオブジェクトに継承されている. |
| 29 | | * 検索キーワードには UTF-8 文字列 ('''unicode オブジェクトではない''') を指定してやる必要がある. |
| 30 | | * 問題なのは,Artists や Authors 等のフィールドが,場合によって amazon.Bag になったり str になったりすること.ちゃんと処理してやらないとハマる. |
| | 30 | == データの整合性 == |
| | 31 | === 変数のあるなし === |
| | 32 | PyAmazon は内部で Amazon API の XML を呼び出して xml.dom.minidom で解析した後,unmarshal という関数で階層構造に沿ってオブジェクトを作っている.そのため,XML の構造がそのまま Python のオブジェクトに継承されている. |
| | 33 | |
| | 34 | そのせいか,結果によってあったりなかったりする要素があるので,適切なエラー処理を書く必要がある. |
| | 35 | |
| | 36 | {{{ |
| | 37 | #!python |
| | 38 | data = amazon.searchByBlended(unicode('のだめ', 'euc-jp').encode('utf-8')) |
| | 39 | d = data.ProductLine[0].ProductInfo.Details[0] |
| | 40 | |
| | 41 | d.ProductDescription # AttributeError を引き起こす可能性が高い |
| | 42 | getattr(d, 'ProductDescription', None) # こちらの方が安全 |
| | 43 | }}} |
| | 44 | |
| | 45 | === 型の整合性 === |
| | 46 | たとえば Artists.Artist の中身が list になったり str になったりする.ちゃんと処理してやらないとハマる. |
| | 47 | |
| | 48 | {{{ |
| | 49 | #!python |
| | 50 | ATTRS = ['Authors', 'Artists', 'Tracks'] |
| | 51 | |
| | 52 | data = amazon.searchByBlended(unicode('のだめ', 'euc-jp').encode('utf-8')) |
| | 53 | d = data.ProductLine[2].ProductInfo.Details[0] |
| | 54 | |
| | 55 | for attr in ATTRS: |
| | 56 | print '%s: ' % attr |
| | 57 | authors = getattr(d, attr, None) |
| | 58 | if isinstance(authors, amazon.Bag): |
| | 59 | authors = getattr(authors, attr[:-1], None) |
| | 60 | if isinstance(authors, list): # リストの場合 |
| | 61 | for a in authors: |
| | 62 | print ' %s' % a |
| | 63 | elif authors is not None: # リストでも None でもない場合は str と仮定 |
| | 64 | print ' %s' % authors |
| | 65 | }}} |