-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.py
420 lines (362 loc) · 15.3 KB
/
server.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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# Copyright 2016 John J. Rofrano. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import datetime
import os
import redis
import re
from redis.exceptions import ConnectionError
from flask import Flask, Response, jsonify, request, json
# Create Flask application
app = Flask(__name__)
# Status Codes
HTTP_200_OK = 200
HTTP_201_CREATED = 201
HTTP_204_NO_CONTENT = 204
HTTP_400_BAD_REQUEST = 400
HTTP_403_ACCESS_FORBIDDEN = 403
HTTP_404_NOT_FOUND = 404
HTTP_409_CONFLICT = 409
######################################################################
# GET INDEX
######################################################################
@app.route('/')
def index():
return jsonify(name='Banking System REST API Service', version='1.0', url='/accounts'), HTTP_200_OK
######################################################################
# LIST ALL ACCOUNTS WITHOUT A CERTAIN NAME :/accounts
# LIST ALL ACCOUNTS WITH A CERTAIN NAME: /accounts?name=john
# LIST ALL ACCOUNTS WITH A CERTAIN ACCOUNT-TYPE: /accounts?type=1
# LIST ALL ACCOUNTS WITH A STATUS ACTIVE: /accounts?active=true
######################################################################
@app.route('/accounts', methods=['GET'])
def list_accounts():
name = request.args.get('name')
type = request.args.get('type')
active = request.args.get('active')
if name:
message = []
for key in redis_server.keys():
account = redis_server.hgetall(key)
if account.has_key('name'):
if account.get('name')==name:
message.append(account)
rc = HTTP_200_OK
if not message:
message = { 'error' : 'Account under name: %s is not found' % name }
rc = HTTP_404_NOT_FOUND
elif type:
message = []
for key in redis_server.keys():
account = redis_server.hgetall(key)
if account.has_key('accounttype'):
if account.get('accounttype')==type:
message.append(account)
rc = HTTP_200_OK
if not message:
message = { 'error' : 'Accounts with type: %s not found' % type }
rc = HTTP_404_NOT_FOUND
elif active:
message = []
for key in redis_server.keys():
account = redis_server.hgetall(key)
if account.has_key('active'):
if account.get('active') == active:
message.append(account)
rc = HTTP_200_OK
if not message:
message = { 'error' : 'Accounts with status: %s not found' % active}
rc = HTTP_404_NOT_FOUND
else :
message = []
rc = HTTP_200_OK
for key in redis_server.keys():
if (key == 'nextId'):
continue
account = redis_server.hgetall(key)
message.append(account)
return reply(message, rc)
######################################################################
# RETRIEVE AN ACCOUNT WITH ID
######################################################################
@app.route('/accounts/<id>', methods=['GET'])
def get_account_by_id(id):
message = []
if id == 'nextId':
message = {'error' : 'Account id: %s is not found' % id }
rc = HTTP_404_NOT_FOUND
elif redis_server.exists(id):
message = redis_server.hgetall(id)
rc = HTTP_200_OK
if not message:
message = { 'error' : 'Account id: %s is not found' % id }
rc = HTTP_404_NOT_FOUND
return reply(message, rc)
######################################################################
# DEACTIVATE AN ACCOUNT WITH ID
######################################################################
# the link used to be /accounts/<id>/deactive, which should be /accounts/<id>/deactivate
# /accounts/<id>/deactive is still used in the bluemix link
# It will be corrected in the hw2
@app.route('/accounts/<id>/deactivate', methods=['PUT'])
def deactivate_account_by_id(id):
message = []
for account in redis_server.keys():
if account == 'nextId':
continue
if account == id:
redis_server.hset(id, 'active', 'false')
message = redis_server.hgetall(account)
rc = HTTP_200_OK
if not message:
message = { 'error' : 'Account id: %s is not found' % id }
rc = HTTP_404_NOT_FOUND
return reply(message, rc)
######################################################################
# CREATE AN ACCOUNT
######################################################################
@app.route('/accounts', methods=['POST'])
def create_account():
payload = []
try:
payload = json.loads(request.data)
except Exception as err:
return reply({'error' : format(err)}, HTTP_400_BAD_REQUEST)
missing_params = find_missing_params(payload)
if not missing_params:
#validations here
validated_balance = validate_balance(payload['balance'])
if validated_balance[0] is 'false':
message = {'error' : validated_balance[1]}
rc = HTTP_400_BAD_REQUEST
return reply(message, rc)
validated_active = validate_active(payload['active'])
if validated_active[0] is 'false':
message = {'error' : validated_active[1]}
rc = HTTP_400_BAD_REQUEST
return reply(message, rc)
#end validations
# start name validation
input_name = payload['name']
if input_name.strip() == "":
message = {'error' : 'Invalid name.'}
rc = HTTP_400_BAD_REQUEST
return reply(message, rc)
words = input_name.split(" ");
for word in words:
if not word.isalpha():
message = {'error' : 'Invalid name.'}
rc = HTTP_400_BAD_REQUEST
return reply(message, rc)
# end name validation
id = redis_server.hget('nextId', 'nextId')
redis_server.hset('nextId','nextId',int(id) + 1)
redis_server.hset(id, 'id', id)
redis_server.hset(id, 'name', payload['name'])
redis_server.hset(id, 'balance', validated_balance[2])
redis_server.hset(id, 'active', validated_active[2])
created_time = (datetime.datetime.now() - datetime.timedelta(hours=5)).strftime("%Y-%m-%d %H:%M:%S")
redis_server.hset(id, 'created_time', created_time)
redis_server.hset(id, 'last_updated_time', created_time)
#Check if payload contains accounttype else assign 0 as a default value
if payload.has_key('accounttype'):
redis_server.hset(id, 'accounttype', payload['accounttype'])
else:
redis_server.hset(id, 'accounttype', 0)
message = redis_server.hgetall(id)
rc = HTTP_201_CREATED
else:
message = { 'error' : 'Missing or invalid %s' % missing_params }
rc = HTTP_400_BAD_REQUEST
return reply(message, rc)
######################################################################
# UPDATE AN EXISTING ACCOUNT
######################################################################
@app.route('/accounts/<id>', methods=['PUT'])
def update_account(id):
payload = []
try:
payload = json.loads(request.data)
except Exception as err:
return reply({"error" : format(err)}, HTTP_400_BAD_REQUEST)
if id == 'nextId':
message = {'error' : 'Account %s is not found' % id}
rc = HTTP_404_NOT_FOUND
elif find_missing_params(payload):
message = { 'error' : 'Missing or invalid %s' % find_missing_params(payload) }
rc = HTTP_400_BAD_REQUEST
elif redis_server.exists(id):
# not allowed to change created_time
if payload.has_key('created_time'):
message = {'error' : 'Field created_time is not allowed to change'}
rc = HTTP_400_BAD_REQUEST
return reply(message, rc)
# not allowed to change last_updated_time
if payload.has_key('last_updated_time'):
message = {'error' : 'Field last_updated_time is not allowed to change'}
rc = HTTP_400_BAD_REQUEST
return reply(message, rc)
#validation
validated_balance = validate_balance(payload['balance'])
if validated_balance[0] is 'false':
message = {'error' : validated_balance[1]}
rc = HTTP_400_BAD_REQUEST
return reply(message, rc)
validated_active = validate_active(payload['active'])
if validated_active[0] is 'false':
message = {'error' : validated_active[1]}
rc = HTTP_400_BAD_REQUEST
return reply(message, rc)
#end validation
# start name validation
input_name = payload['name']
if input_name.strip() == "":
message = {'error' : 'Invalid name.'}
rc = HTTP_400_BAD_REQUEST
return reply(message, rc)
words = input_name.split(" ");
for word in words:
if not word.isalpha():
message = {'error' : 'Invalid name.'}
rc = HTTP_400_BAD_REQUEST
return reply(message, rc)
# end name validation
redis_server.hset(id, 'name', payload['name'])
redis_server.hset(id, 'active', validated_active[2])
redis_server.hset(id, 'balance', validated_balance[2])
redis_server.hset(id, 'last_updated_time', (datetime.datetime.now() - datetime.timedelta(hours=5)).strftime("%Y-%m-%d %H:%M:%S"))
#Check if payload contains accounttype
if payload.has_key('accounttype'):
redis_server.hset(id, 'accounttype', payload['accounttype'])
message = redis_server.hgetall(id)
rc = HTTP_200_OK
else:
message = { 'error' : 'Account id: %s was not found' % id }
rc = HTTP_404_NOT_FOUND
return reply(message, rc)
######################################################################
# DELETE AN ACCOUNT
######################################################################
@app.route('/accounts/<id>', methods=['DELETE'])
def delete_account(id):
if redis_server.exists(id):
redis_server.delete(id)
return '', HTTP_204_NO_CONTENT
######################################################################
# U T I L I T Y F U N C T I O N S
######################################################################
def reply(message, rc):
response = Response(json.dumps(message))
response.headers['Content-Type'] = 'application/json'
response.status_code = rc
return response
# NEED THREE FIELDS TO BE NOT NULL: name, balance, active
def find_missing_params(data):
missing_params = []
if not data.has_key('active'):
missing_params.append('active')
if not data.has_key('balance'):
missing_params.append('balance')
if not data.has_key('name'):
missing_params.append('name')
if data.has_key('accounttype'):
if data['accounttype'] not in {0,1,2,3}:
missing_params.append('accounttype')
return missing_params
# Returns a list - first element is whether it passed validation, second is message, third is transformed data
def validate_balance(balance):
balance = str(balance)
is_a_number = re.compile("^(-)?((((\d){1,3},(\d){1,3})+(,(\d){1,3})?(\.(\d)+)?)|((\d)+(\.)*(\d)+)|(\d)+)$")
if is_a_number.match(balance):
is_negative = re.compile("^-(.)*$")
if is_negative.match(balance):
return ('false', 'Negative values not allowed in balance parameter', balance)
too_many_decimals = re.compile("^(\d)*\.(\d){3,}$")
if too_many_decimals.match(balance):
return ('false', 'More than two digits after the decimal in balance parameter', balance)
if ',' in balance:
balance = re.sub(',', '', balance)
is_an_int = re.compile("^(\d+)$")
if is_an_int.match(balance):
balance += '.0'
too_few_decimals = re.compile("^(\d)*\.\d$")
if too_few_decimals.match(balance):
balance += '0'
return ("true", "processed", balance)
else:
return ('false', 'Not a valid number for balance parameter', balance)
# Returns a list - first element is whether it passed validation, second is message, third is transformed data
def validate_active(active):
active = str(active).lower()
if (active == 'true' or active == 't' or active == '1'):
return ('true', 'valid', 'true')
elif (active == 'false' or active == 'f' or active == '0'):
return ('true', 'valid', 'false')
return ('false', 'Not a valid value for active parameter', active)
######################################################################
# Connect to Redis and catch connection exceptions
######################################################################
def connect_to_redis(hostname, port, password):
try:
redis_server = redis.Redis(host=hostname, port=port, password=password)
redis_server.ping()
except Exception:
redis_server = None
return redis_server
if not redis_server.exists('nextId'):
redis_server.hset('nextId','nextId',len(redis_server.keys()) + 1)
return redis_server
######################################################################
# INITIALIZE Redis
# This method will work in the following conditions:
# 1) In Bluemix with Redsi bound through VCAP_SERVICES
# 2) With Redis running on the local server as with Travis CI
# 3) With Redis --link ed in a Docker container called 'redis'
######################################################################
def inititalize_redis():
global redis_server
redis_server = None
# Get the crdentials from the Bluemix environment
if 'VCAP_SERVICES' in os.environ:
print "Using VCAP_SERVICES..."
VCAP_SERVICES = os.environ['VCAP_SERVICES']
services = json.loads(VCAP_SERVICES)
creds = services['rediscloud'][0]['credentials']
print "Conecting to Redis on host %s port %s" % (creds['hostname'], creds['port'])
redis_server = connect_to_redis(creds['hostname'], creds['port'], creds['password'])
else:
print "VCAP_SERVICES not found, checking localhost for Redis"
redis_server = connect_to_redis('127.0.0.1', 6379, None)
if not redis_server:
print "No Redis on localhost, pinging: redis"
response = os.system("ping -c 1 redis")
if response == 0:
print "Connecting to remote: redis"
redis_server = connect_to_redis('redis', 6379, None)
if not redis_server:
# if you end up here, redis instance is down.
print '*** FATAL ERROR: Could not connect to the Redis Service'
exit(1)
# Get the next ID
def get_next_id():
return redis_server.hget('nextId', 'nextId')
######################################################################
# M A I N
######################################################################
if __name__ == "__main__":
inititalize_redis()
# this line is used to empty database
# redis_server.flushdb()
# Get bindings from the environment
port = os.getenv('PORT', '5000')
app.run(host='0.0.0.0', port=int(port), debug=True)