Skip to content

Commit 17a5a68

Browse files
authored
Merge pull request #7 from Adam-WL/python3-compat-updates
Updates for Python 3 compatibility
2 parents e21b337 + 01573dc commit 17a5a68

File tree

5 files changed

+106
-45
lines changed

5 files changed

+106
-45
lines changed

.travis.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
language: python
22
python:
3-
- '2.7'
3+
- '3.10'
44
install: pip install -r setup/requirements.txt
55
script: cd test; nosetests
66
before_install:

setup/requirements.txt

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
Flask==0.10.1
2-
money==1.3.0
3-
oauthlib==1.0.3
4-
requests==2.9.1
5-
tabulate
1+
flask~=3.0.0
2+
requests~=2.31.0
3+
oauthlib~=3.2.2
4+
money~=1.3.0
5+
tabulate~=0.9.0

src/groupsplit.py

Lines changed: 41 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ def split(total, num_people):
5757

5858
def do_hash(msg):
5959
m = hashlib.md5()
60-
m.update(msg)
60+
m.update(msg.encode('utf-8'))
6161
return m.hexdigest()
6262

6363
class Splitwise:
@@ -99,14 +99,18 @@ def get_client(self):
9999

100100
webbrowser.open_new(uri)
101101

102-
proc = subprocess.Popen(['python', 'server.py'], stdout=subprocess.PIPE)
103-
stdout, stderr = proc.communicate()
104-
if stderr:
105-
exit(stderr)
102+
# proc = subprocess.Popen(['python', 'server.py'], stdout=subprocess.PIPE)
103+
# stdout, stderr = proc.communicate()
104+
# if stderr:
105+
# exit(stderr)
106+
107+
verifier_input = input('Copy the oauth verifier from the success page in the browser window : ')
108+
106109
client = oauthlib.oauth1.Client(self.ckey, client_secret=self.csecret,
107110
resource_owner_key=oauth_token,
108111
resource_owner_secret=oauth_secret,
109-
verifier=stdout.strip())
112+
verifier=verifier_input)
113+
#verifier=stdout.strip()) #bYpMPennhuz6bqMRZXd8
110114

111115
uri, headers, body = client.sign("https://secure.splitwise.com/api/v3.0/get_access_token",
112116
http_method='POST')
@@ -117,7 +121,8 @@ def get_client(self):
117121
client = oauthlib.oauth1.Client(self.ckey, client_secret=self.csecret,
118122
resource_owner_key=oauth_token,
119123
resource_owner_secret=oauth_secret,
120-
verifier=stdout.strip())
124+
verifier=verifier_input)
125+
#verifier=stdout.strip())
121126
with open('oauth_client.pkl', 'wb') as pkl:
122127
pickle.dump(client, pkl)
123128
self.client = client
@@ -160,24 +165,24 @@ def get_expenses(self, after_date="", limit=0, allow_deleted=True):
160165

161166
class CsvSettings():
162167
def __init__(self, rows):
163-
print "These are the first two rows of your csv"
164-
print '\n'.join([str(t) for t in rows[0:2]])
165-
print 'Colnum numbers start at 0'
168+
print("These are the first two rows of your csv")
169+
print("\n".join([str(t) for t in rows[0:2]]))
170+
print("Colnum numbers start at 0")
166171
self.date_col = input("Which column has the date?")
167172
self.amount_col = input("Which column has the amount?")
168173
self.desc_col = input("Which column has the description?")
169-
self.has_title_row = raw_input("Does first row have titles? [Y/n]").lower() != 'n'
174+
self.has_title_row = input("Does first row have titles? [Y/n]").lower() != 'n'
170175
self.newest_transaction = ''
171176
while True:
172177
try:
173-
self.local_currency = raw_input("What currency were these transactions made in?").upper()
178+
self.local_currency = input("What currency were these transactions made in?").upper()
174179
test = Money("1.00", self.local_currency) #pylint: disable=W0612
175180
except ValueError as err:
176-
print err
177-
print "Try again..."
181+
print(err)
182+
print("Try again...")
178183
else:
179184
break
180-
self.remember = raw_input("Remember these settings? [Y/n]").lower() != 'n'
185+
self.remember = input("Remember these settings? [Y/n]").lower() != 'n'
181186

182187
def __del__(self):
183188
if self.remember:
@@ -198,7 +203,7 @@ def __init__(self, options, args, api):
198203
self.api = api
199204
self.options = options
200205
self.args = args
201-
with open(csv_file, 'rb') as csvfile:
206+
with open(csv_file, 'r') as csvfile:
202207
reader = csv.reader(csvfile)
203208
self.rows = [x for x in reader]
204209

@@ -224,15 +229,17 @@ def make_transactions(self):
224229
**change csvDateFormat to the format in your csv if necessary**
225230
Further reading on date formats: https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
226231
"""
227-
csvDateFormat="%m/%d/%y"
232+
csvDateFormat="%m/%d/%Y"
228233
self.transactions = []
229234
for r in self.rows:
230-
if not self.options.try_all and do_hash(str(r)) == self.csv.newest_transaction:
231-
break
232-
if float(r[self.csv.amount_col]) < 0:
233-
self.transactions.append({"date": datetime.strftime(datetime.strptime(r[self.csv.date_col], csvDateFormat), "%Y-%m-%dT%H:%M:%SZ"),
234-
"amount": -1 * Money(r[self.csv.amount_col], self.csv.local_currency),
235-
"desc": re.sub('\s+',' ', r[self.csv.desc_col])}
235+
# if not self.options.try_all and do_hash(str(r)) == self.csv.newest_transaction:
236+
# break
237+
if float(r[int(self.csv.amount_col)]) > 0:
238+
self.transactions.append({
239+
"date": datetime.strptime(r[int(self.csv.date_col)], csvDateFormat).strftime("%Y-%m-%dT%H:%M:%SZ"),
240+
"amount": Money(r[int(self.csv.amount_col)], self.csv.local_currency),
241+
"desc": re.sub(r'\s+', ' ', r[int(self.csv.desc_col)])
242+
}
236243
)
237244

238245
def get_group(self, name):
@@ -269,19 +276,19 @@ def ask_for_splits(self):
269276
add it to tee list of transactions to upload to Splitwise. Gets final
270277
confirmation before returning.
271278
"""
272-
print "Found {0} transactions".format(len(self.transactions))
279+
print("Found {0} transactions".format(len(self.transactions)))
273280
i = 0
274281
for t in self.transactions:
275-
if self.options.yes or raw_input("%d: %s at %s $%s. Split? [y/N]" % (i, t['date'], t['desc'], t['amount'])).lower() == 'y':
282+
if self.options.yes or input("%d: %s at %s $%s. Split? [y/N]" % (i, t['date'], t['desc'], t['amount'])).lower() == 'y':
276283
self.splits.append(t)
277284

278-
print "-" * 40
279-
print "Your Chosen Splits"
280-
print "-" * 40
281-
print tabulate( self.splits, headers={"date":"Date", "amount":"Amount", "desc":"Description"} )
285+
print("-" * 40)
286+
print("Your Chosen Splits")
287+
print("-" * 40)
288+
print(tabulate( self.splits, headers={"date":"Date", "amount":"Amount", "desc":"Description"} ))
282289

283290
# Kill program if user doesn't want to submit splits
284-
assert self.options.yes or raw_input( "Confirm submission? [y/N]" ).lower() == 'y', "User canceled submission"
291+
assert self.options.yes or input( "Confirm submission? [y/N]" ).lower() == 'y', "User canceled submission"
285292

286293
def __getitem__(self, index):
287294
"""
@@ -309,7 +316,7 @@ def __getitem__(self, index):
309316
params['users__%s__paid_share' % (i+1)] = 0
310317
params['users__%s__owed_share' % (i+1)] = (base + one_cent).amount if extra.amount > 0 else base.amount
311318
extra -= one_cent
312-
paramsStr = urllib.urlencode(params)
319+
paramsStr = urllib.parse.urlencode(params)
313320
return "https://secure.splitwise.com/api/v3.0/create_expense?%s" % (paramsStr)
314321

315322

@@ -326,14 +333,15 @@ def main():
326333
logger.setLevel(log_levels[options.verbosity])
327334
splitwise = Splitwise(options.api_client)
328335
split_gen = SplitGenerator(options, args, splitwise)
329-
print "Uploading splits"
336+
print("Uploading splits")
330337
for uri in split_gen:
331338
if options.dryrun:
332-
print uri
339+
print(uri)
333340
continue
334341
splitwise.post_expense(uri)
335342
sys.stdout.write("\n")
336343
sys.stdout.flush()
337344

345+
338346
if __name__ == "__main__":
339347
main()

src/server.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,16 @@
33

44

55
def shutdown_server():
6-
func = request.environ.get('werkzeug.server.shutdown')
7-
if func is None:
8-
raise RuntimeError('Not running with the Werkzeug Server')
9-
func()
6+
# func = request.environ.get('werkzeug.server.shutdown')
7+
# if func is None:
8+
# raise RuntimeError('Not running with the Werkzeug Server')
9+
# func()
10+
return True
1011

1112
@app.route('/')
1213
def authorize():
13-
print request.args['oauth_verifier']
14+
#print(request.args['oauth_verifier'])
15+
print(request)
1416
shutdown_server()
1517
return "Thank you, you can close the tab"
1618

@@ -19,4 +21,4 @@ def test():
1921
return "Hello!"
2022

2123
if __name__ == "__main__":
22-
app.run()
24+
app.run(debug=True)

test/all_categories_list.csv

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
id,name
2+
1,Utilities
3+
48,Cleaning
4+
5,Electricity
5+
6,Heat/gas
6+
11,Other
7+
37,Trash
8+
8,TV/Phone/Internet
9+
7,Water
10+
2,Uncategorized
11+
18,General
12+
19,Entertainment
13+
20,Games
14+
21,Movies
15+
22,Music
16+
23,Other
17+
24,Sports
18+
25,Food and drink
19+
13,Dining out
20+
12,Groceries
21+
38,Liquor
22+
26,Other
23+
27,Home
24+
39,Electronics
25+
16,Furniture
26+
14,Household supplies
27+
17,Maintenance
28+
4,Mortgage
29+
28,Other
30+
29,Pets
31+
3,Rent
32+
30,Services
33+
31,Transportation
34+
46,Bicycle
35+
32,Bus/train
36+
15,Car
37+
33,Gas/fuel
38+
47,Hotel
39+
34,Other
40+
9,Parking
41+
35,Plane
42+
36,Taxi
43+
40,Life
44+
50,Childcare
45+
41,Clothing
46+
49,Education
47+
42,Gifts
48+
10,Insurance
49+
43,Medical expenses
50+
44,Other
51+
45,Taxes

0 commit comments

Comments
 (0)