Open mailtobash opened 3 years ago
👋 @mailtobash I don't believe we have something like this in the python SDK, though we do have similar methods in some of the other SDKs (though they're not well-maintained at this point in time).
I'll leave this open so we can track interest, but I don't have an ETA on when this would be released.
If anyone is interested, below is how I implemented a JSON serializer to convert to JSON and write a JSON array to a file.
from datetime import datetime, date
from braintree import Environment, Configuration, TransactionSearch
from braintree.attribute_getter import AttributeGetter
from braintree.status_event import StatusEvent
from braintree.braintree_gateway import BraintreeGateway
import json
def braintree_object_tree_to_dict(braintree_object):
data = braintree_object.__dict__.copy()
for key, value in data.items():
if isinstance(value, AttributeGetter):
data[key] = braintree_object_tree_to_dict(value)
return data
def encode_bt_transaction_json(obj):
# Serialize date times into ISO with Z
if isinstance(obj, datetime):
return str(obj.isoformat()) + "Z"
if isinstance(obj, date):
return str(obj.isoformat()) + "Z"
# Do not attempt to serialize methods
# Culprit being CreditCard.expired that is not useful because it is a helper method
# that gets all expired cards from the server. We have expiration in credit_card object
if hasattr(obj, '__call__'):
return None
# Custom serialization for StatusEvent
if isinstance(obj, StatusEvent):
return {"timestamp": obj.timestamp, "amount": obj.amount, "status": obj.status,
"user": str(obj.user) if hasattr(obj, "user") else "", "transaction_source": obj.transaction_source}
# Useless object we dont need it
if isinstance(obj, BraintreeGateway):
return None
raise TypeError(str(type(obj)) + " is not JSON serializable")
# Invocation to the method above:
gateway = BraintreeGateway(Configuration(Environment.Sandbox, merchant_id=merch_id, pub_key,pvt_key))
interval_start=datetime(2009, 1, 1)
interval_end=datetime.datetime(2011, 1, 1)
# search function
search_results = gateway.transaction.search(TransactionSearch.created_at.between(interval_start, interval_end))
try:
json_results_arr = []
if search_results:
for result in search_results.items:
data = braintree_object_tree_to_dict(result)
json_result = simplejson.dumps(data, iterable_as_array=True, use_decimal=True,
default=encode_bt_transaction_json, indent=4)
json_results_arr.append(json_result)
# Create JSON string comma separated
json_string = ",".join(json_results_arr)
# Write as a JSON array
json_string = "[" + json_string + "]"
# Write the file
with open(file_path, 'a') as outfile:
outfile.write(json_string)
except Exception as e:
raise Exception("Exception: " + str(e))
for internal tracking, ticket 1941
This is something we are looking for as well please
If anyone is still interested in modifying braintree objects to dict or json, here is my solution:
def braintree_object_to_dict(braintree_object):
"""
Recursively convert a Braintree object and its nested objects to a dictionary.
"""
if isinstance(braintree_object, (Configuration, AddOnGateway, BraintreeGateway)):
return None
data = braintree_object.__dict__.copy()
for key, value in data.items():
if isinstance(value, AttributeGetter):
data[key] = braintree_object_to_dict(value)
elif isinstance(value, Decimal):
data[key] = float(value)
elif isinstance(value, (datetime, date)):
data[key] = str(value.isoformat()) + "Z"
elif hasattr(value, "__dict__"): # Handle nested objects
data[key] = braintree_object_to_dict(value)
elif isinstance(value, list): # Handle lists of objects
data[key] = [braintree_object_to_dict(item) if hasattr(item, "__dict__") else
(float(item) if isinstance(item, Decimal)
else str(item.isoformat()) + "Z" if isinstance(item, (datetime, date))
else item) for item in
value]
# Remove private attributes if necessary
data.pop('_setattrs', None)
return data
We are writing a connector to write JSON files of transactions that we search in the past day. Version 3.57.1
Returns :
Is there a way to format it as JSON? I tried emulating the
__repr__
method but it is still printing bjects like StatuEvent as<StatusEvent ..... at 1214132321>
Here is what I tried:
Thank you