Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ language: python
python:
- 2.6
- 2.7
- 3.3
install:
- python setup.py develop
- pip install -r requirements.txt
Expand Down
2 changes: 1 addition & 1 deletion balanced/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from __future__ import unicode_literals


__version__ = '1.0.1'

Expand Down
6 changes: 3 additions & 3 deletions balanced/config.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from __future__ import unicode_literals

from datetime import datetime

import simplejson as json
Expand Down Expand Up @@ -71,8 +71,8 @@ def _serialize(self, data):
@staticmethod
def _parse_deserialized(e):
if isinstance(e, dict):
for k in e.iterkeys():
if k.endswith('_at') and isinstance(e[k], basestring):
for k in e.keys():
if k.endswith('_at') and isinstance(e[k], str):
e[k] = iso8601.parse_date(e[k])
return e

Expand Down
14 changes: 7 additions & 7 deletions balanced/exc.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import unicode_literals

import httplib

import http.client

import wac

Expand All @@ -10,7 +10,7 @@ class BalancedError(Exception):
def __str__(self):
attrs = ', '.join([
'{0}={1}'.format(k, repr(v))
for k, v in self.__dict__.iteritems()
for k, v in self.__dict__.items()
])
return '{0}({1})'.format(self.__class__.__name__, attrs)

Expand Down Expand Up @@ -42,22 +42,22 @@ def __new__(meta_cls, name, bases, dikt):
cls.types = [
getattr(cls, k)
for k in dir(cls)
if k.isupper() and isinstance(getattr(cls, k), basestring)
if k.isupper() and isinstance(getattr(cls, k), str)
]
cls.type_to_error.update(zip(cls.types, [cls] * len(cls.types)))
cls.type_to_error.update(list(zip(cls.types, [cls] * len(cls.types))))
return cls

def __init__(self, requests_ex):
super(wac.Error, self).__init__(requests_ex)
self.status_code = requests_ex.response.status_code
data = getattr(requests_ex.response, 'data', {})
for k, v in data.get('errors', [{}])[0].iteritems():
for k, v in data.get('errors', [{}])[0].items():
setattr(self, k, v)

@classmethod
def format_message(cls, requests_ex):
data = getattr(requests_ex.response, 'data', {})
status = httplib.responses[requests_ex.response.status_code]
status = http.client.responses[requests_ex.response.status_code]
error = data['errors'][0]
status = error.pop('status', status)
status_code = error.pop('status_code',
Expand Down
20 changes: 10 additions & 10 deletions balanced/resources.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from __future__ import unicode_literals


import uritemplate
import wac
Expand All @@ -21,7 +21,7 @@ class ObjectifyMixin(wac._ObjectifyMixin):
def _objectify(self, resource_cls, **fields):
# setting values locally, not from server
if 'links' not in fields:
for key, value in fields.iteritems():
for key, value in fields.items():
setattr(self, key, value)
else:
self._construct_from_response(**fields)
Expand All @@ -31,11 +31,11 @@ def _construct_from_response(self, **payload):
meta = payload.pop('meta', None)

if isinstance(self, wac.Page):
for key, value in meta.iteritems():
for key, value in meta.items():
setattr(self, key, value)

# the remaining keys here are just hypermedia resources
for _type, resources in payload.iteritems():
for _type, resources in payload.items():
# Singular resources are represented as JSON objects. However,
# they are still wrapped inside an array:
cls = Resource.registry[_type]
Expand All @@ -48,7 +48,7 @@ def _construct_from_response(self, **payload):
target = self
else:
target = cls()
for key, value in resource_body.iteritems():
for key, value in resource_body.items():
if key in ('links',):
continue
setattr(target, key, value)
Expand All @@ -66,7 +66,7 @@ def _hydrate(cls, payload):
Construct links for objects
"""
links = payload.pop('links', {})
for key, uri in links.iteritems():
for key, uri in links.items():
variables = uritemplate.variables(uri)
# marketplaces.card_holds
collection, resource_type = key.split('.')
Expand Down Expand Up @@ -103,7 +103,7 @@ def extract_variables_from_item(item, variables):
# check if this is a collection or a singular item
if any(
parsed_link.endswith(value)
for value in item_variables.itervalues()
for value in item_variables.values()
):
# singular
if not item_property.endswith('_href'):
Expand Down Expand Up @@ -162,7 +162,7 @@ def save(self):

attrs = dict(
(k, v.href if isinstance(v, Resource) else v)
for k, v in attrs.iteritems()
for k, v in attrs.items()
if not isinstance(v, (cls.collection_cls))
)

Expand All @@ -178,10 +178,10 @@ def delete(self):
self.client.delete(self.href)

def __dir__(self):
return self.__dict__.keys()
return list(self.__dict__.keys())

def __getattr__(self, item):
if isinstance(item, basestring):
if isinstance(item, str):
suffix = '_href'
if suffix not in item:
href = getattr(self, item + suffix, None)
Expand Down
4 changes: 2 additions & 2 deletions balanced/utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from __future__ import unicode_literals



class ClassPropertyDescriptor(object):
Expand Down Expand Up @@ -33,7 +33,7 @@ def classproperty(func):


def extract_href_from_object(obj):
if isinstance(obj, basestring):
if isinstance(obj, str):
return obj
if isinstance(obj, dict):
return obj['href']
Expand Down
16 changes: 8 additions & 8 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@
master_doc = 'index'

# General information about the project.
project = u'balanced'
copyright = u'2012, Balanced'
project = 'balanced'
copyright = '2012, Balanced'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
Expand Down Expand Up @@ -187,8 +187,8 @@
# (source start file, target name, title, author,
# documentclass [howto/manual]).
latex_documents = [
('index', 'balanced.tex', u'balanced Documentation',
u'Balanced', 'manual'),
('index', 'balanced.tex', 'balanced Documentation',
'Balanced', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
Expand Down Expand Up @@ -217,8 +217,8 @@
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'balanced', u'balanced Documentation',
[u'Balanced'], 1)
('index', 'balanced', 'balanced Documentation',
['Balanced'], 1)
]

# If true, show URL addresses after external links.
Expand All @@ -231,8 +231,8 @@
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'balanced', u'balanced Documentation',
u'Balanced', 'balanced', 'One line description of project.',
('index', 'balanced', 'balanced Documentation',
'Balanced', 'balanced', 'One line description of project.',
'Miscellaneous'),
]

Expand Down
14 changes: 7 additions & 7 deletions examples/accounting.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,16 @@ def generate_report(args):
if not os.path.exists('./cache'):
os.makedirs('./cache')

print 'Downloading Debits'
print('Downloading Debits')
debits = balanced.Debit.query.all()

print 'Downloading Credits'
print('Downloading Credits')
credits = balanced.Credit.query.all()

print 'Downloading Refunds'
print('Downloading Refunds')
refunds = balanced.Refund.query.all()

print 'Caching Transactions'
print('Caching Transactions')
with open('cache/debits.obj', 'w') as f:
pickle.dump(debits, f)

Expand All @@ -66,10 +66,10 @@ def group(xs, head, tail):

# {year: [(month, txn)]}
txns_by_year = group(txns_by_period,
lambda (y, m, txn): y,
lambda (y, m, txn): (m, txn))
lambda y_m_txn: y_m_txn[0],
lambda y_m_txn2: (y_m_txn2[1], y_m_txn2[2]))

group_by_month = lambda xs: group(xs, lambda (a, b): a, lambda (a, b): b)
group_by_month = lambda xs: group(xs, lambda a_b: a_b[0], lambda a_b1: a_b1[1])

# {year: {month: [txn]}}
txns_by_year_by_month = {key: group_by_month(txns_by_year[key])
Expand Down
16 changes: 8 additions & 8 deletions examples/bank_account_debits.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'''
Learn how to verify a bank account so you can debit with it.
'''
from __future__ import unicode_literals


import balanced

Expand All @@ -24,20 +24,20 @@ def main():
customer = balanced.Customer().save()
bank_account.associate_to_customer(customer)

print 'you can\'t debit until you authenticate'
print('you can\'t debit until you authenticate')
try:
bank_account.debit(100)
except balanced.exc.HTTPError as ex:
print 'Debit failed, %s' % ex.message
print('Debit failed, %s' % ex.message)

# verify
verification = bank_account.verify()

print 'PROTIP: for TEST bank accounts the valid amount is always 1 and 1'
print('PROTIP: for TEST bank accounts the valid amount is always 1 and 1')
try:
verification.confirm(amount_1=1, amount_2=2)
except balanced.exc.BankAccountVerificationFailure as ex:
print 'Authentication error , %s' % ex.message
print('Authentication error , %s' % ex.message)

# reload
verification = balanced.BankAccount.fetch(
Expand All @@ -48,11 +48,11 @@ def main():
raise Exception('unpossible')
debit = bank_account.debit(100)

print 'debited the bank account %s for %d cents' % (
print('debited the bank account %s for %d cents' % (
debit.source.href,
debit.amount
)
print 'and there you have it'
))
print('and there you have it')


if __name__ == '__main__':
Expand Down
38 changes: 19 additions & 19 deletions examples/events_and_callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@
got good news for you. Run this example below to see how to get yourself some
callback goodness and to understand how events work.
"""
from __future__ import unicode_literals

import time

import balanced

from helpers import RequestBinClient
from .helpers import RequestBinClient


def init():
Expand All @@ -21,54 +21,54 @@ def main():
init()
request_bin = RequestBinClient()

print 'let\'s create a callback'
print('let\'s create a callback')
balanced.Callback(
url=request_bin.callback_url,
).save()

print 'let\'s create a card and associate it with a new account'
print('let\'s create a card and associate it with a new account')
card = balanced.Card(
expiration_month='12',
csc='123',
number='5105105105105100',
expiration_year='2020',
).save()

print 'generate a debit (which implicitly creates and captures a hold)'
print('generate a debit (which implicitly creates and captures a hold)')
card.debit(100)

print 'event creation is an async operation, let\'s wait until we have ' \
'some events!'
print('event creation is an async operation, let\'s wait until we have ' \
'some events!')
while not balanced.Event.query.count():
print 'Zzzz'
print('Zzzz')
time.sleep(0)

print 'Woop, we got some events, let us see what there is to look at'
print('Woop, we got some events, let us see what there is to look at')
for event in balanced.Event.query:
print 'this was a {0} event, it occurred at {1}, the callback has a ' \
print('this was a {0} event, it occurred at {1}, the callback has a ' \
'status of {2}'.format(
event.type,
event.occurred_at,
event.callback_statuses
)
))

print 'you can inspect each event to see the logs'
print('you can inspect each event to see the logs')
event = balanced.Event.query.first()
for callback in event.callbacks:
print 'inspecting callback to {0} for event {1}'.format(
print('inspecting callback to {0} for event {1}'.format(
callback.url,
event.type,
)
))
for log in callback.logs:
print 'this attempt to the callback has a status "{0}"'.format(
print('this attempt to the callback has a status "{0}"'.format(
log.status
)
))

print 'ok, let\'s check with requestb.in to see if our callbacks fired'
print 'we received {0} callbacks, you can view them at {1}'.format(
print('ok, let\'s check with requestb.in to see if our callbacks fired')
print('we received {0} callbacks, you can view them at {1}'.format(
len(request_bin.get_requests()),
request_bin.view_url,
)
))


if __name__ == '__main__':
Expand Down
Loading