【发布时间】:2021-06-29 09:19:21
【问题描述】:
我有一个与 Stripe 集成的 Django 应用程序。根据Stripe documentation,我遵循他们的建议,使用 try/except 子句来处理在创建客户、产品、价格等过程中可能出现的任何错误。
为了保持 DRY,我创建了一个 Python 基类,特定于对象的子类从该基类继承。这样我可以自定义每个子类的 create_method 来创建一个特定的对象,但仍然将所有错误处理保留在一个地方(父类)。这一切似乎都运行良好,但我想知道是否有人对此方法有任何反馈或建议改进?谢谢!
import stripe
from django.conf import settings
stripe.api_key = settings.STRIPE_SECRET_KEY
class StripeObject():
"""
Base class for all Stripe objects (e.g., Customer, Product, Price)
"""
create_method = None
def __init__(self, common_kwargs={}, instance_kwargs={}):
self.common_kwargs = common_kwargs
self.instance_kwargs = instance_kwargs
def handle_error(self, e):
try:
print('Code is: %s' % e.code)
print('Message is: %s' % e.user_message)
except KeyError:
print('One of the following keys was not found in the error response:\ncode or user_message.')
def create(self):
try:
return self.create_method(**self.common_kwargs, **self.instance_kwargs)
except stripe.error.RateLimitError as e:
# Too many requests made to the API too quickly
self.handle_error(e)
except stripe.error.InvalidRequestError as e:
# Invalid parameters were supplied to Stripe's API
self.handle_error(e)
except stripe.error.AuthenticationError as e:
# Authentication with Stripe's API failed
# (maybe you changed API keys recently)
self.handle_error(e)
except stripe.error.APIConnectionError as e:
# Network communication with Stripe failed
self.handle_error(e)
except stripe.error.StripeError as e:
# Display a very generic error to the user, and maybe send
# yourself an email
self.handle_error(e)
except Exception as e:
# Something else happened, completely unrelated to Stripe
self.handle_error(e)
class StripeCustomer(StripeObject):
create_method = stripe.Customer.create
class StripeProduct(StripeObject):
create_method = stripe.Product.create
class StripePrice(StripeObject):
create_method = stripe.Price.create
def __init__(self, instance_kwargs):
common_kwargs = {
"currency": "usd"
}
super().__init__(common_kwargs=common_kwargs, instance_kwargs=instance_kwargs)
这些类的结果接口是:
product = StripeProduct({"name":"Product Name"}).create()
【问题讨论】:
标签: python django oop stripe-payments