-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
152 lines (141 loc) · 5.85 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import decimal
from flask import Flask
from flask import request
import psycopg2
import json
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
return str(o)
return super(DecimalEncoder, self).default(o)
app = Flask(__name__)
conn = psycopg2.connect("dbname=transactionsdb user=postgres host=192.168.99.100 password=postgres")
cur = conn.cursor()
# use login_required here
@app.route('/deposit', methods=['POST'])
def deposit():
assert request.path == '/deposit'
assert request.method == 'POST'
try:
data = json.loads(request.data)
except json.JSONDecodeError:
return json.dumps({'message': 'Please Enter the Input in the JSON format correctly'})
try:
assert len(data) == 2
except AssertionError:
return json.dumps({'message': 'Remove any additional fields other than account and amount'})
try:
account = data['account']
amount = int(data["amount"])
except KeyError:
return json.dumps({'message': 'Please Enter the Input in 2 fields. account and amount. both strings'})
try:
cur.execute("UPDATE balances SET balance = balance + %s WHERE account_no = %s;", (amount, account))
conn.commit()
except psycopg2.Error as e:
conn.rollback()
print(e.pgerror)
cur.execute("SELECT balance FROM balances WHERE account_no=%s;", (account,))
balance = cur.fetchone()
return json.dumps({'account': account, 'balance': balance, 'message': 'success'}, cls=DecimalEncoder)
@app.route('/transfer', methods=['POST'])
def transfer():
# if user.ongoingtransaction:
# return "You sent request multiple times" or drop the transaction
# user.ongoingtransaction = True
assert request.path == '/transfer'
assert request.method == 'POST'
try:
data = json.loads(request.data)
except json.JSONDecodeError:
return json.dumps({'message': 'Please Enter the Input in the JSON format correctly'})
try:
from_account = data['from_account']
to_account = data["to_account"]
except KeyError:
return json.dumps({'message': 'Please Enter the Input in 3 fields. from_account, to_account and amount. all '
'strings'})
try:
amount = int(data["amount"])
except ValueError:
return json.dumps({'message': 'Please Enter a Number for input'})
try:
assert len(data) == 3
except AssertionError:
return json.dumps({'message': 'Remove any additional fields other than from_account, to_account and amount'})
try:
assert amount > 0
except AssertionError:
return json.dumps({'message': 'Please Enter Positive Values of Amount'})
errormsg = "Oops! Something wrong on our servers. Don't worry. Your transaction is already rolled back."
try:
cur.execute("call transact(%s,%s,%s,null);", (from_account, to_account, amount))
except psycopg2.IntegrityError as e:
conn.rollback()
if e.pgcode == '23514':
return json.dumps({'message': "Balance Insufficient"})
if e.pgcode == '23503':
return json.dumps({'message': "No Such Accounts present in the System. Please Check if you entered the "
"proper Account Number"})
else:
print(e.pgcode, e.pgerror)
return json.dumps({"message": errormsg})
except psycopg2.OperationalError as e:
conn.rollback()
print(e.pgcode, e.pgerror)
return json.dumps({"message": errormsg})
except psycopg2.InternalError as e:
conn.rollback()
print(e.pgcode, e.pgerror)
return json.dumps({"message": errormsg})
except psycopg2.ProgrammingError as e:
conn.rollback()
print(e.pgcode, e.pgerror)
return json.dumps({"message": errormsg})
except psycopg2.DatabaseError as e:
conn.rollback()
print(e.pgcode, e.pgerror)
return json.dumps({"message": errormsg})
except psycopg2.Error as e:
conn.rollback()
print(e.pgerror, e.pgcode)
return json.dumps({"message": errormsg})
""" This one works too...
cur.execute("create or replace function transact(fromacc varchar,toacc varchar, amt numeric) RETURNS uuid as $$ "
"update balances set balance = balance - amt where account_no = fromacc;"
"select balance from balances where account_no = fromacc;"
"update balances set balance = balance + amt where account_no = toacc;"
"INSERT INTO transactions(amount, credit_account_no, debit_account_no) "
"VALUES (amt, toacc, fromacc) RETURNING id;"
"-- EXCEPTION WHEN UNIQUE_VIOLATION THEN -- "
"inserted in concurrent session.-- RAISE NOTICE 'Transaction ID already exists!'; "
"$$ "
"LANGUAGE sql;")
"""
conn.commit()
transaction_id = cur.fetchone()
cur.execute(f"select balance from balances where account_no = '{from_account}';")
from_balance = cur.fetchone()
cur.execute(f"select balance from balances where account_no = '{to_account}';")
to_balance = cur.fetchone()
transaction_id_clean = [data for data in transaction_id][0]
cur.execute(f"select created_datetime from transactions where id = '{transaction_id_clean}';")
created_at = cur.fetchone()
response = {
"id": transaction_id,
"from": {
"id": from_account,
"balance": from_balance
},
"to": {
"id": to_account,
"balance": to_balance
},
"transfered": amount,
"created_datetime": created_at,
"message": "Success"
}
# user.ongoingtransaction = False
return json.dumps(response, cls=DecimalEncoder, default=str)
if __name__ == '__main__':
app.run()