Python w/Stripe:如何从收费响应中获取有效的JSON?

GSt*_*Sto 5 python json stripe-payments

我有一个名为python包装器的方法succeed,如下所示:

def succeed(handler, data):
"""Send the given |data| dict as a JSON response in |handler.response|."""
set_headers(handler)
handler.response.write(json.dumps(data))
Run Code Online (Sandbox Code Playgroud)

我试图传递Stripe API调用的结果,使用此方法将信用卡收回另一个服务.这是方法调用,在另一个类中:

succeed(self, dict(success=True, charge_id=charge.id, response=charge))
Run Code Online (Sandbox Code Playgroud)

当我这样做时,我得到'充电不是JSON可序列化'错误.如何使用此代码将所有费用ID响应作为JSON传递?以下是完整的回复:

    TypeError: <Charge charge id=ch_103Tsv2kD9PLZlzDG5ce7TE1 at 0x113003b50> JSON: {
  "amount": 3500, 
  "amount_refunded": 0, 
  "balance_transaction": "xxxxxx", 
  "captured": true, 
  "card": {
    "address_city": null, 
    "address_country": null, 
    "address_line1": null, 
    "address_line1_check": null, 
    "address_line2": null, 
    "address_state": null, 
    "address_zip": null, 
    "address_zip_check": null, 
    "country": "US", 
    "customer": null, 
    "cvc_check": "pass", 
    "exp_month": 5, 
    "exp_year": 2015, 
    "fingerprint": "xxxxxxxxxxxxxx", 
    "last4": "4242", 
    "name": "stackoverflow@example.com", 
    "object": "card", 
    "type": "Visa"
  }, 
  "created": 1392181282, 
  "currency": "usd", 
  "customer": null, 
  "description": "X0G0 FEOMSI NA", 
  "dispute": null, 
  "failure_code": null, 
  "failure_message": null, 
  "invoice": null, 
  "livemode": false, 
  "metadata": {
    "email": "stackoverflow@exmple.com"
  }, 
  "object": "charge", 
  "paid": true, 
  "refunded": false, 
  "refunds": []
}
Run Code Online (Sandbox Code Playgroud)

Liy*_*ang 6

使用该.to_dict()方法将条带充电对象转换为python字典.

序列化词典是留给读者的练习.


作为一个额外的有趣点,我强烈建议使用dir它:它可以让你看到所有可能的属性和方法.

例如:

>>> import stripe
>>> dir(stripe.Charge)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'all', 'capture', 'class_name', 'class_url', 'clear', 'close_dispute', 'construct_from', 'copy', 'create', 'fromkeys', 'get', 'has_key', 'instance_url', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'refresh', 'refresh_from', 'refund', 'request', 'retrieve', 'save', 'serialize', 'serialize_metadata', 'setdefault', 'stripe_id', 'to_dict', 'update', 'update_dispute', 'values', 'viewitems', 'viewkeys', 'viewvalues']
>>>
Run Code Online (Sandbox Code Playgroud)

从这里你可以看到to_dict方法.您也可以看到该serialize方法,但我不清楚它的作用.

更多文档

  • 实际上,在我使用的条带库版本中,这确实有点浅层序列化.我能够通过这个来解决这个问题:json.loads(str(stripe_object))为你提供了一个没有条带对象的真实字典,只有纯数据. (5认同)