-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrest_app.py
77 lines (71 loc) · 2.95 KB
/
rest_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
from flask import Flask, request, jsonify, Response
import db_connector
import os
import signal
app = Flask(__name__)
# using route and then based on method returning appropriate result.
@app.route('/users')
@app.route('/users/<user_id>', methods=['GET','POST','PUT','DELETE'])
def user(user_id):
if request.method == 'POST':
try:
request_data = request.json
user_name = request_data.get('user_name')
conn = db_connector.get_con()
conn.autocommit(True)
cursor = conn.cursor()
query =f"INSERT into sql8641160.users (user_name, user_id) VALUES ('{user_name}',{user_id})"
cursor.execute(query)
cursor.close()
conn.close()
return jsonify({ "status":"ok", "user_added":user_name }), 200 # status code
except:
return jsonify({"status": "error", "reason": "id already exists"}), 500 # status code
elif request.method == 'GET':
try:
conn = db_connector.get_con()
cursor = conn.cursor()
query =f"SELECT user_name FROM sql8641160.users WHERE user_id = {user_id}"
cursor.execute(query)
cursor.scroll(o,mode='absolute')
user = cursor.fetchone()
#user = str(cursor.fetchall()[0])
cursor.close()
conn.close()
return jsonify({ "status":"ok", "user_name":user }), 200 # status code
except:
return jsonify({"status": "error", "reason": "no such id"}), 500 # status code
elif request.method == 'PUT':
try:
request_data = request.json
user_name = request_data.get('user_name')
conn = db_connector.get_con()
conn.autocommit(True)
cursor = conn.cursor()
query = f"UPDATE sql8641160.users SET user_name = '{user_name}' WHERE user_id = {user_id}"
cursor.execute(query)
cursor.close()
conn.close()
return jsonify({ "status":"ok", "user_updated":user_id }), 200 # status code
except:
return jsonify({"status": "error", "reason": "no such id"}), 500 # status code
elif request.method == 'DELETE':
try:
conn = db_connector.get_con()
conn.autocommit(True)
cursor = conn.cursor()
query = f"DELETE FROM sql8641160.users WHERE user_id = {user_id}"
cursor.execute(query)
cursor.close()
conn.close()
return jsonify({ "status":"ok", "user_deleted":user_id }), 200 # status code
except:
return jsonify({"status": "error", "reason": "no such id"}), 500 # status code
@app.route('/stop_server')
def stop_server():
os.kill(os.getpid(), signal.SIGINT)
return 'Server stopped'
# host is pointing at local machine address
# debug is used for more detailed logs + hot swaping
# the desired port - feel free to change
app.run(host='127.0.0.1', debug=True, port=5000)