LoginSignup
2
1

More than 5 years have passed since last update.

Webpay の Entity 型を Dict 型に変換する (Python で再帰的に)

Last updated at Posted at 2015-12-14

Webpay、あんまり流行ってる気がしないんですが少し使ってみてます。

ドキュメントがわかりやすいように見えて、もやっとしているため結局理解するのに少し時間がかかっちゃいますね。

Python バインディングが用意されていて(pipでインストールできる)、比較的簡単にリクエストができます。

import webpay

client = webpay.WebPay(settings.WEBPAY_SECRET)
response = client.customer.create(card=token)

こんな感じで。

この、response 変数に入ってるのが webpay の Entity 型 (webpay.data_types.Entity) というやつで、内容は辞書に似ているんですが、各値がクラス変数に展開されています。JavaScript のオブジェクトみたいな感じです。

それが入れ子になっているので、ログに書こうとすると非常にめんどくさい。
一応、__str__ が実装されていて、yaml に似たそれなりに構造化された文字列が返ってくるのですが、改行なども含まれるため少し扱いに緊張します。パーサも書かかない限り、再利用性は低そうです。

そこで。再帰的に辞書型に変換してしまえば、扱いが楽になると思います。

from webpay.data_types import Entity


def webpay_entity_to_dict(webpay_entity):
    """
    webpay の Entity 型を再帰的に Dict に変換
    """
    if isinstance(webpay_entity, list):
        return [webpay_entity_to_dict(e) for e in webpay_entity]
    if not isinstance(webpay_entity, Entity):
        return webpay_entity
    return {key: webpay_entity_to_dict(value) for key, value
            in webpay_entity.__dict__.items()}

これを通せば辞書型にできますので、json.dumps() してからログに出したりとか、シリアライズしやすくなるかと。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1