-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrest.py
More file actions
75 lines (57 loc) · 2.19 KB
/
rest.py
File metadata and controls
75 lines (57 loc) · 2.19 KB
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
#!/usr/bin/env python
import cgi
import psycopg2
import json
DBNAME = 'postgres'
HOST = 'localhost'
USER = 'user'
PASSWORD = 'user'
#---------- DB Tab&Fun QUERYs ----------#
def callDBtableview(schema,table):
conn = psycopg2.connect(dbname=DBNAME, host=HOST, user=USER, password=PASSWORD)
cur = conn.cursor()
cur.execute('SELECT * FROM "'+schema+'"."'+table+'" ')
colnames = [desc[0] for desc in cur.description]
results = []
for row in cur.fetchall():
results.append(dict(zip(colnames, row)))
return json.dumps(results, indent=2)
def callDBfunction(schema,fun,params):
conn = psycopg2.connect(dbname=DBNAME, host=HOST, user=USER, password=PASSWORD)
cur = conn.cursor()
cur.execute('SELECT * FROM "'+schema+'"."'+fun+'"('+params+')')
colnames = [desc[0] for desc in cur.description]
results = []
for row in cur.fetchall():
results.append(dict(zip(colnames, [str(r) for r in row])))
return json.dumps(results, indent=2)
form = cgi.FieldStorage()
val1 = form.getvalue('first')
#---------- Generate JSON Response ----------#
print "Content-type: application/json"
print "Status: 200 OK"
print "Content-Type: application/json"
print "Access-Control-Allow-Origin: *"
body = json.dumps({'name':'Duccio'})
body = json.dumps({})
arguments = cgi.FieldStorage()
if arguments.has_key('type'):
if arguments['type'].value == 'tab':
body = callDBtableview(arguments['schema'].value,arguments['obj'].value)
elif arguments['type'].value == 'fun':
params = ""
if arguments.has_key('params'):
params += arguments['params'].value[1:-1].replace(":",":=")
body = callDBfunction(arguments['schema'].value,arguments['obj'].value, params)
else:
body = json.dumps( { 'Error' : 'Wrong type parameters, must be: type=tab or type=fun'} )
else:
body = json.dumps( {'Error' : 'Wrong parameters, must be ?type=[tab/fun]&schema=[schema_name]&obj=[table_name/function_name]¶ms=(p1:1,p2:2,...,pn=n)'} )
print "Content-Length: %d" % (len(body))
print ""
print body
#print """Content-type: text/html
#
#<html><head><title>Test URL Encoding</title></head><body>
#Hello my name is %s
#</body></html>""" % (val1)