-
Notifications
You must be signed in to change notification settings - Fork 3
/
tes.py
117 lines (96 loc) · 2.69 KB
/
tes.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
import falcon
import MySQLdb
import json
import settings
class TesResource:
def on_get(self, req, resp):
try:
db = MySQLdb.connect(**settings.dbConfig)
cursor = db.cursor(MySQLdb.cursors.DictCursor)
q = ("SELECT * FROM tes")
cursor.execute(q)
rows = cursor.fetchall()
output = {'tes': []}
for row in rows:
data = {
"id": row['id'],
"field1": row['field1'],
"field2": row['field2']
}
output['tes'].append(data)
resp.status = falcon.HTTP_200
resp.body = json.dumps(output, encoding='utf-8')
cursor.close()
db.close()
except Exception as e:
resp.body = json.dumps({'error':str(e)})
resp.status = falcon.HTTP_500
return resp
def on_post(self, req, resp):
try:
db = MySQLdb.connect(**settings.dbConfig)
cursor = db.cursor()
raw_json = req.stream.read()
data = json.loads(raw_json, encoding='utf-8')
q = """INSERT INTO tes (field1, field2) VALUES(%s,%s)"""
cursor.execute(q, (data['field1'], data['field2']))
db.commit()
cursor.close()
output = {
'status': "Data berhasil disimpan"
}
resp.status = falcon.HTTP_200
data_resp = json.dumps(output, encoding='utf-8')
resp.body = data_resp
db.close()
except Exception as e:
db.rollback()
resp.body = json.dumps({'error':str(e)})
resp.status = falcon.HTTP_500
return resp
def on_put(self, req, resp):
try:
db = MySQLdb.connect(**settings.dbConfig)
cursor = db.cursor()
raw_json = req.stream.read()
data = json.loads(raw_json, encoding='utf-8')
q = """UPDATE `tes` SET `field1`=%s, `field2`=%s WHERE id=%s"""
cursor.execute(q, (data['field1'], data['field2'], data['id']))
db.commit()
cursor.close()
output = {
'status': "Data berhasil diubah"
}
resp.status = falcon.HTTP_200
data_resp = json.dumps(output, encoding='utf-8')
resp.body = data_resp
db.close()
except Exception as e:
db.rollback()
resp.body = json.dumps({'error':str(e)})
resp.status = falcon.HTTP_500
return resp
def on_delete(self, req, resp):
try:
id = req.get_param('id')
if id is None or id == "":
resp.body = json.dumps({'error':'Parameter id kosong'})
resp.status = falcon.HTTP_500
return resp
db = MySQLdb.connect(**settings.dbConfig)
cursor = db.cursor()
q = """DELETE FROM `tes` WHERE id=%s"""
cursor.execute(q, (id,))
db.commit()
cursor.close()
output = {
'status': "Data berhasil dihapus"
}
resp.status = falcon.HTTP_200
data_resp = json.dumps(output, encoding='utf-8')
resp.body = data_resp
except Exception as e:
db.rollback()
resp.body = json.dumps({'error':str(e)})
resp.status = falcon.HTTP_500
return resp