我正在研究Braintree订阅,以便检索客户ID和与这些ID相关的订阅价格。在我的代码中,我遵循this post的建议。
这是我的代码的摘录:
gateway = braintree.BraintreeGateway(
braintree.Configuration(
environment=braintree.Environment.Production,
merchant_id= 'our_merchant_id',
public_key='our_public_key',
private_key='our_private_key'
)
)
subscriptions = gateway.subscription.search(
braintree.SubscriptionSearch.status.in_list(
braintree.Subscription.Status.Active,
braintree.Subscription.Status.PastDue,
braintree.Subscription.Status.Pending
)
)
result = {}
for subscription in subscriptions.items:
payment_method = gateway.payment_method.find(subscription.payment_method_token)
result[payment_method.customer_id] = subscription.price
"""do something with result """
这种方法在BT沙箱和大约100条记录的小型查询中效果很好。但是,每当我尝试查询约120个以上的订阅时,BT服务器始终会以504错误进行响应。我想在生产中一次查询约5000个订阅。有什么建议么?
跟踪:
Traceback (most recent call last):
File "BT_subscrAmount.py", line 22, in <module>
for subscription in subscriptions.items:
File "/home/karen/miniconda3/lib/python3.6/site-
packages/braintree/resource_collection.py", line 38, in items
for item in self.__method(self.__query, batch):
File "/home/karen/miniconda3/lib/python3.6/site-
packages/braintree/subscription_gateway.py", line 79, in __fetch
response = self.config.http().post(self.config.base_merchant_path() +
"/subscriptions/advanced_search", {"search": criteria})
File "/home/karen/miniconda3/lib/python3.6/site-
packages/braintree/util/http.py", line 56, in post
return self.__http_do("POST", path, Http.ContentType.Xml, params)
File "/home/karen/miniconda3/lib/python3.6/site-
packages/braintree/util/http.py", line 86, in __http_do
Http.raise_exception_from_status(status)
File "/home/karen/miniconda3/lib/python3.6/site-
packages/braintree/util/http.py", line 49, in raise_exception_from_status
raise UnexpectedError("Unexpected HTTP_RESPONSE " + str(status))
braintree.exceptions.unexpected_error.UnexpectedError: Unexpected
HTTP_RESPONSE 504
答案 0 :(得分:0)
将查询分成小批(5000个以上的订阅,成为50个100个订阅的调用),然后在返回响应时进行汇总。许多API都对速率限制和响应限制进行了硬编码。
答案 1 :(得分:0)
在一位出色的BT支持工程师的帮助下,我们终于能够找到解决问题的方法。
说明:
当BT返回搜索结果时,它们会收集所有相关数据,并向客户端返回一个大型(序列化的)响应对象。在我们的例子中,某些订阅具有大量关联的事务,这使得获取,序列化它们以及将它们返回给客户端的过程很慢。发出请求时,BT网关以50为一组返回页面,默认超时为60秒。具有多个大型响应对象的任何组都可能会超时并产生504错误。
解决方案:
为避免这种延迟,我们可以使用ResourceCollections class中的id方法来代替items方法,而只返回对象的id。使用单个订阅ID,我们可以获取单个订阅,并且仅获取所需的属性,如下所示:
subscriptions = gateway.subscription.search(
braintree.SubscriptionSearch.status.in_list(
braintree.Subscription.Status.Active
)
)
subscription_ids = subscriptions.ids
def find_customer_id(id):
subscription = gateway.subscription.find(id)
payment_method = gateway.payment_method.find(subscription.payment_method_token)
return (payment_method.customer_id, subscription.price)
希望这对其他人有帮助!