Mercurial > hg > ChinaGisRestApi
annotate RestDbInterface.py @ 43:562717546168
refactoring...
RestDbGisApi and
RestDbJsonStore inherit from
RestDbInterface
author | casties |
---|---|
date | Thu, 02 Sep 2010 13:17:23 +0200 |
parents | f94fc5a51a38 |
children | c6c47034d2a4 |
rev | line source |
---|---|
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
1 ''' |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
2 Created on 19.5.2010 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
3 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
4 @author: casties |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
5 ''' |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
6 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
7 from OFS.Folder import Folder |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
8 from Products.PageTemplates.PageTemplateFile import PageTemplateFile |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
9 from Products.ZSQLExtend import ZSQLExtend |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
10 import logging |
15 | 11 import re |
16 | 12 import psycopg2 |
18 | 13 import json |
36 | 14 import time |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
15 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
16 from zope.interface import implements |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
17 from zope.publisher.interfaces import IPublishTraverse |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
18 from ZPublisher.BaseRequest import DefaultPublishTraverse |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
19 #from zope.publisher.interfaces import NotFound |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
20 #from zope.app import zapi |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
21 #from zope.component import queryMultiAdapter |
4
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
22 import Shared.DC.ZRDB.DA |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
23 from Products.ZSQLMethods.SQL import SQLConnectionIDs |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
24 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
25 |
16 | 26 def getTextFromNode(node): |
14 | 27 """get the cdata content of a XML node""" |
16 | 28 if node is None: |
14 | 29 return "" |
16 | 30 |
31 if isinstance(node, list): | |
32 nodelist = node | |
33 else: | |
34 nodelist=node.childNodes | |
35 | |
14 | 36 rc = "" |
37 for node in nodelist: | |
38 if node.nodeType == node.TEXT_NODE: | |
39 rc = rc + node.data | |
40 return rc | |
41 | |
16 | 42 def sqlName(s,lc=True): |
43 """returns restricted ASCII-only version of string""" | |
15 | 44 if s is None: |
45 return "" | |
46 | |
47 # all else -> "_" | |
16 | 48 s = re.sub(r'[^A-Za-z0-9_]','_',s) |
15 | 49 if lc: |
50 return s.lower() | |
51 | |
52 return s | |
14 | 53 |
31 | 54 gisToSqlTypeMap = { |
55 "text": "text", | |
32 | 56 "number": "numeric", |
31 | 57 "id": "text", |
32 | 58 "gis_id": "text", |
59 "coord_lat": "numeric", | |
60 "coord_lon": "numeric" | |
31 | 61 } |
62 | |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
63 class RestDbInterface(Folder): |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
64 """Object for RESTful database queries |
7 | 65 path schema: /db/{schema}/{table}/ |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
66 omitting table gives a list of schemas |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
67 omitting table and schema gives a list of schemas |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
68 """ |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
69 implements(IPublishTraverse) |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
70 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
71 meta_type="RESTdb" |
4
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
72 manage_options=Folder.manage_options+( |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
73 {'label':'Config','action':'manage_editRestDbInterfaceForm'}, |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
74 ) |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
75 |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
76 # management templates |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
77 manage_editRestDbInterfaceForm=PageTemplateFile('zpt/editRestDbInterface',globals()) |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
78 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
79 # data templates |
8 | 80 XML_index = PageTemplateFile('zpt/XML_index', globals()) |
81 XML_schema = PageTemplateFile('zpt/XML_schema', globals()) | |
82 XML_schema_table = PageTemplateFile('zpt/XML_schema_table', globals()) | |
83 HTML_index = PageTemplateFile('zpt/HTML_index', globals()) | |
84 HTML_schema = PageTemplateFile('zpt/HTML_schema', globals()) | |
85 HTML_schema_table = PageTemplateFile('zpt/HTML_schema_table', globals()) | |
22 | 86 JSONHTML_index = PageTemplateFile('zpt/JSONHTML_index', globals()) |
87 JSONHTML_schema = PageTemplateFile('zpt/JSONHTML_schema', globals()) | |
88 JSONHTML_schema_table = PageTemplateFile('zpt/JSONHTML_schema_table', globals()) | |
24 | 89 # JSON_* templates are scripts |
30 | 90 def JSON_index(self,data): |
91 """JSON index function""" | |
92 self.REQUEST.RESPONSE.setHeader("Content-Type", "application/json") | |
93 json.dump(data, self.REQUEST.RESPONSE) | |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
94 |
30 | 95 def JSON_schema(self,data,schema): |
96 """JSON index function""" | |
97 self.REQUEST.RESPONSE.setHeader("Content-Type", "application/json") | |
98 json.dump(data, self.REQUEST.RESPONSE) | |
99 | |
100 def JSON_schema_table(self,data,tablename): | |
101 """JSON index function""" | |
102 self.REQUEST.RESPONSE.setHeader("Content-Type", "application/json") | |
103 json.dump(data, self.REQUEST.RESPONSE) | |
104 | |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
105 |
4
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
106 def __init__(self, id, title, connection_id=None): |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
107 """init""" |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
108 self.id = id |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
109 self.title = title |
4
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
110 # database connection id |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
111 self.connection_id = connection_id |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
112 # create template folder |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
113 self.manage_addFolder('template') |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
114 |
4
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
115 |
22 | 116 def getJsonString(self,object): |
117 """returns a JSON formatted string from object""" | |
118 return json.dumps(object) | |
119 | |
17 | 120 def getCursor(self,autocommit=True): |
4
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
121 """returns fresh DB cursor""" |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
122 conn = getattr(self,"_v_database_connection",None) |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
123 if conn is None: |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
124 # create a new connection object |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
125 try: |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
126 if self.connection_id is None: |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
127 # try to take the first existing ID |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
128 connids = SQLConnectionIDs(self) |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
129 if len(connids) > 0: |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
130 connection_id = connids[0][0] |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
131 self.connection_id = connection_id |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
132 logging.debug("connection_id: %s"%repr(connection_id)) |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
133 |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
134 da = getattr(self, self.connection_id) |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
135 da.connect('') |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
136 # we copy the DAs database connection |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
137 conn = da._v_database_connection |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
138 #conn._register() # register with the Zope transaction system |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
139 self._v_database_connection = conn |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
140 except Exception, e: |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
141 raise IOError("No database connection! (%s)"%str(e)) |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
142 |
5 | 143 cursor = conn.getcursor() |
17 | 144 if autocommit: |
145 # is there a better version to get to the connection? | |
146 cursor.connection.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) | |
147 | |
4
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
148 return cursor |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
149 |
17 | 150 def executeSQL(self, query, args=None, hasResult=True, autocommit=True): |
4
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
151 """execute query with args on database and return all results. |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
152 result format: {"fields":fields, "rows":data}""" |
16 | 153 logging.debug("executeSQL query=%s args=%s"%(query,args)) |
17 | 154 cur = self.getCursor(autocommit=autocommit) |
4
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
155 cur.execute(query, args) |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
156 # description of returned fields |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
157 fields = cur.description |
17 | 158 if hasResult: |
159 # get all data in an array | |
160 data = cur.fetchall() | |
161 cur.close() | |
162 return {"fields":fields, "rows":data} | |
163 else: | |
164 cur.close() | |
165 return None | |
16 | 166 |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
167 def publishTraverse(self,request,name): |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
168 """change the traversal""" |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
169 # get stored path |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
170 path = request.get('restdb_path', []) |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
171 logging.debug("publishtraverse: name=%s restdb_path=%s"%(name,path)) |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
172 |
13 | 173 if name in ("index_html", "PUT"): |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
174 # end of traversal |
13 | 175 if request.get("method") == "POST" and request.get("action",None) == "PUT": |
176 # fake PUT by POST with action=PUT | |
177 name = "PUT" | |
178 | |
179 return getattr(self, name) | |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
180 #TODO: should we check more? |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
181 else: |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
182 # traverse |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
183 if len(path) == 0: |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
184 # first segment |
8 | 185 if name == 'db': |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
186 # virtual path -- continue traversing |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
187 path = [name] |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
188 request['restdb_path'] = path |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
189 else: |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
190 # try real path |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
191 tr = DefaultPublishTraverse(self, request) |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
192 ob = tr.publishTraverse(request, name) |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
193 return ob |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
194 else: |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
195 path.append(name) |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
196 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
197 # continue traversing |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
198 return self |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
199 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
200 def index_html(self,REQUEST,RESPONSE): |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
201 """index method""" |
8 | 202 # ReST path was stored in request |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
203 path = REQUEST.get('restdb_path',[]) |
36 | 204 |
8 | 205 # type and format are real parameter |
26 | 206 resultFormat = REQUEST.get('format','HTML').upper() |
27 | 207 queryType = REQUEST.get('type',None) |
36 | 208 |
26 | 209 logging.debug("index_html path=%s resultFormat=%s queryType=%s"%(path,resultFormat,queryType)) |
8 | 210 |
26 | 211 if queryType is not None: |
212 # non-empty queryType -- look for template | |
213 pt = getattr(self.template, "%s_%s"%(resultFormat,queryType), None) | |
8 | 214 if pt is not None: |
26 | 215 return pt(format=resultFormat,type=queryType,path=path) |
8 | 216 |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
217 if len(path) == 1: |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
218 # list of schemas |
26 | 219 return self.showListOfSchemas(resultFormat=resultFormat) |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
220 elif len(path) == 2: |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
221 # list of tables |
26 | 222 return self.showListOfTables(resultFormat=resultFormat,schema=path[1]) |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
223 elif len(path) == 3: |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
224 # table |
25 | 225 if REQUEST.get("method") == "POST" and REQUEST.get("create_table_file",None) is not None: |
24 | 226 # POST to table to check |
26 | 227 return self.checkTable(resultFormat=resultFormat,schema=path[1],table=path[2]) |
24 | 228 # else show table |
26 | 229 return self.showTable(resultFormat=resultFormat,schema=path[1],table=path[2]) |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
230 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
231 # don't know what to do |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
232 return str(REQUEST) |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
233 |
12 | 234 def PUT(self, REQUEST, RESPONSE): |
235 """ | |
236 Implement WebDAV/HTTP PUT/FTP put method for this object. | |
237 """ | |
13 | 238 logging.debug("RestDbInterface PUT") |
239 #logging.debug("req=%s"%REQUEST) | |
12 | 240 #self.dav__init(REQUEST, RESPONSE) |
241 #self.dav__simpleifhandler(REQUEST, RESPONSE) | |
13 | 242 # ReST path was stored in request |
243 path = REQUEST.get('restdb_path',[]) | |
244 if len(path) == 3: | |
245 schema = path[1] | |
246 tablename = path[2] | |
247 file = REQUEST.get("create_table_file",None) | |
248 if file is None: | |
249 RESPONSE.setStatus(400) | |
250 return | |
4
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
251 |
30 | 252 fields = None |
253 fieldsStr = REQUEST.get("create_table_fields",None) | |
254 logging.debug("put with schema=%s table=%s file=%s fields=%s"%(schema,tablename,file,repr(fieldsStr))) | |
255 if fieldsStr is not None: | |
256 # unpack fields | |
257 fields = [{"name":n, "type": t} for (n,t) in [f.split(":") for f in fieldsStr.split(",")]] | |
31 | 258 |
28 | 259 ret = self.createTableFromXML(schema, tablename, file, fields) |
26 | 260 # return the result as JSON |
261 format = REQUEST.get("format","JSON") | |
262 if format == "JSON": | |
20 | 263 RESPONSE.setHeader("Content-Type", "application/json") |
264 json.dump(ret, RESPONSE) | |
26 | 265 |
266 elif format == "JSONHTML": | |
20 | 267 RESPONSE.setHeader("Content-Type", "text/html") |
268 RESPONSE.write("<html>\n<body>\n<pre>") | |
269 json.dump(ret, RESPONSE) | |
270 RESPONSE.write("</pre>\n</body>\n</html>") | |
13 | 271 |
272 else: | |
273 # 400 Bad Request | |
274 RESPONSE.setStatus(400) | |
275 return | |
12 | 276 |
26 | 277 def showTable(self,resultFormat='XML',schema='public',table=None,REQUEST=None,RESPONSE=None): |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
278 """returns PageTemplate with tables""" |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
279 logging.debug("showtable") |
38 | 280 if REQUEST is None: |
281 REQUEST = self.REQUEST | |
282 | |
23 | 283 # should be cross-site accessible |
25 | 284 if RESPONSE is None: |
285 RESPONSE = self.REQUEST.RESPONSE | |
38 | 286 |
23 | 287 RESPONSE.setHeader('Access-Control-Allow-Origin', '*') |
38 | 288 |
22 | 289 # everything else has its own template |
26 | 290 pt = getattr(self.template, '%s_schema_table'%resultFormat, None) |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
291 if pt is None: |
26 | 292 return "ERROR!! template %s_schema_table not found"%resultFormat |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
293 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
294 data = self.getTable(schema,table) |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
295 return pt(data=data,tablename=table) |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
296 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
297 def getTable(self,schema='public',table=None,username='guest'): |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
298 """return table data""" |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
299 logging.debug("gettable") |
16 | 300 data = self.executeSQL('select * from "%s"."%s"'%(schema,table)) |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
301 return data |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
302 |
26 | 303 def hasTable(self,schema='public',table=None,username='guest'): |
304 """return if table exists""" | |
305 logging.debug("hastable") | |
306 data = self.executeSQL('select 1 from information_schema.tables where table_schema=%s and table_name=%s',(schema,table)) | |
307 ret = bool(data['rows']) | |
308 return ret | |
309 | |
310 def showListOfTables(self,resultFormat='XML',schema='public',REQUEST=None,RESPONSE=None): | |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
311 """returns PageTemplate with list of tables""" |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
312 logging.debug("showlistoftables") |
23 | 313 # should be cross-site accessible |
25 | 314 if RESPONSE is None: |
315 RESPONSE = self.REQUEST.RESPONSE | |
23 | 316 RESPONSE.setHeader('Access-Control-Allow-Origin', '*') |
24 | 317 |
26 | 318 pt = getattr(self.template, '%s_schema'%resultFormat, None) |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
319 if pt is None: |
26 | 320 return "ERROR!! template %s_schema not found"%resultFormat |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
321 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
322 data = self.getListOfTables(schema) |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
323 return pt(data=data,schema=schema) |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
324 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
325 def getListOfTables(self,schema='public',username='guest'): |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
326 """return list of tables""" |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
327 logging.debug("getlistoftables") |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
328 # get list of fields and types of db table |
22 | 329 qstr="""SELECT c.relname AS tablename FROM pg_catalog.pg_class c |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
330 LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
331 WHERE c.relkind IN ('r','') AND n.nspname NOT IN ('pg_catalog', 'pg_toast') |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
332 AND pg_catalog.pg_table_is_visible(c.oid)""" |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
333 #qstr="select attname, format_type(pg_attribute.atttypid, pg_attribute.atttypmod) from pg_attribute, pg_class where attrelid = pg_class.oid and pg_attribute.attnum > 0" |
4
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
334 data=self.executeSQL(qstr) |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
335 return data |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
336 |
26 | 337 def showListOfSchemas(self,resultFormat='XML',REQUEST=None,RESPONSE=None): |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
338 """returns PageTemplate with list of schemas""" |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
339 logging.debug("showlistofschemas") |
23 | 340 # should be cross-site accessible |
25 | 341 if RESPONSE is None: |
342 RESPONSE = self.REQUEST.RESPONSE | |
23 | 343 RESPONSE.setHeader('Access-Control-Allow-Origin', '*') |
24 | 344 |
26 | 345 pt = getattr(self.template, '%s_index'%resultFormat, None) |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
346 if pt is None: |
26 | 347 return "ERROR!! template %s_index not found"%resultFormat |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
348 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
349 data = self.getListOfSchemas() |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
350 return pt(data=data) |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
351 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
352 def getListOfSchemas(self,username='guest'): |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
353 """return list of schemas""" |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
354 logging.debug("getlistofschemas") |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
355 # TODO: really look up schemas |
9 | 356 data={'fields': (('schemas',),), 'rows': [('public',),]} |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
357 return data |
14 | 358 |
26 | 359 def checkTable(self,resultFormat,schema,table,REQUEST=None,RESPONSE=None): |
360 """check the table. | |
361 returns valid data fields and table name.""" | |
362 if REQUEST is None: | |
363 REQUEST = self.REQUEST | |
364 RESPONSE = REQUEST.RESPONSE | |
365 | |
366 file = REQUEST.get("create_table_file",None) | |
367 res = self.checkTableFromXML(schema, table, file) | |
368 logging.debug("checkTable result=%s"%repr(res)) | |
369 # return the result as JSON | |
370 if resultFormat == "JSON": | |
371 RESPONSE.setHeader("Content-Type", "application/json") | |
372 json.dump(res, RESPONSE) | |
373 | |
374 elif resultFormat == "JSONHTML": | |
375 RESPONSE.setHeader("Content-Type", "text/html") | |
376 RESPONSE.write("<html>\n<body>\n<pre>") | |
377 json.dump(res, RESPONSE) | |
378 RESPONSE.write("</pre>\n</body>\n</html>") | |
379 | |
380 else: | |
381 return "ERROR: invalid resultFormat" | |
382 | |
383 def checkTableFromXML(self,schema,table,data,REQUEST=None,RESPONSE=None): | |
384 """check the table with the given XML data. | |
385 returns valid data fields and table name.""" | |
386 logging.debug("checkTableFromXML schema=%s table=%s"%(schema,table)) | |
387 # clean table name | |
388 tablename = sqlName(table) | |
389 tableExists = self.hasTable(schema, table) | |
390 if data is None: | |
391 fieldNames = [] | |
392 else: | |
393 # get list of field names from upload file | |
394 fields = self.importExcelXML(schema,tablename,data,fieldsOnly=True) | |
395 | |
396 res = {'tablename': tablename, 'table_exists': tableExists} | |
397 res['fields'] = fields | |
398 return res | |
399 | |
14 | 400 def createEmptyTable(self,schema,table,fields): |
401 """create a table with the given fields | |
402 returns list of created fields""" | |
15 | 403 logging.debug("createEmptyTable") |
14 | 404 sqlFields = [] |
405 for f in fields: | |
406 if isinstance(f,dict): | |
407 # {name: XX, type: YY} | |
408 name = sqlName(f['name']) | |
409 type = f['type'] | |
31 | 410 sqltype = gisToSqlTypeMap[type] |
14 | 411 |
412 else: | |
413 # name only | |
414 name = sqlName(f) | |
415 type = 'text' | |
31 | 416 sqltype = 'text' |
14 | 417 |
31 | 418 sqlFields.append({'name':name, 'type':type, 'sqltype':sqltype}) |
14 | 419 |
43 | 420 self.executeSQL('drop table if exists "%s"."%s"'%(schema,table),hasResult=False) |
421 fieldString = ", ".join(['"%s" %s'%(f['name'],f['sqltype']) for f in sqlFields]) | |
422 sqlString = 'create table "%s"."%s" (%s)'%(schema,table,fieldString) | |
423 logging.debug("createemptytable: SQL=%s"%sqlString) | |
424 self.executeSQL(sqlString,hasResult=False) | |
425 self.setTableMetaTypes(schema,table,sqlFields) | |
426 return sqlFields | |
26 | 427 |
28 | 428 def createTableFromXML(self,schema,table,data, fields=None): |
13 | 429 """create or replace a table with the given XML data""" |
28 | 430 logging.debug("createTableFromXML schema=%s table=%s data=%s fields=%s"%(schema,table,data,fields)) |
17 | 431 tablename = sqlName(table) |
28 | 432 self.importExcelXML(schema, tablename, data, fields) |
17 | 433 return {"tablename": tablename} |
14 | 434 |
28 | 435 def importExcelXML(self,schema,table,xmldata,fields=None,fieldsOnly=False): |
14 | 436 ''' |
437 Import XML file in Excel format into the table | |
438 @param table: name of the table the xml shall be imported into | |
439 ''' | |
440 from xml.dom.pulldom import parseString,parse | |
441 | |
442 namespace = "urn:schemas-microsoft-com:office:spreadsheet" | |
443 containerTagName = "Table" | |
444 rowTagName = "Row" | |
16 | 445 colTagName = "Cell" |
14 | 446 dataTagName = "Data" |
26 | 447 xmlFields = [] |
14 | 448 sqlFields = [] |
16 | 449 numFields = 0 |
14 | 450 sqlInsert = None |
451 | |
452 logging.debug("import excel xml") | |
453 | |
454 ret="" | |
16 | 455 if isinstance(xmldata, str): |
14 | 456 logging.debug("importXML reading string data") |
16 | 457 doc=parseString(xmldata) |
14 | 458 else: |
459 logging.debug("importXML reading file data") | |
16 | 460 doc=parse(xmldata) |
14 | 461 |
462 cnt = 0 | |
463 while True: | |
464 node=doc.getEvent() | |
465 | |
466 if node is None: | |
467 break | |
468 | |
469 else: | |
16 | 470 #logging.debug("tag=%s"%node[1].localName) |
14 | 471 if node[1].localName is not None: |
472 tagName = node[1].localName.lower() | |
473 else: | |
474 # ignore non-tag nodes | |
475 continue | |
16 | 476 |
14 | 477 if tagName == rowTagName.lower(): |
478 # start of row | |
479 doc.expandNode(node[1]) | |
480 cnt += 1 | |
481 if cnt == 1: | |
482 # first row -- field names | |
483 names=node[1].getElementsByTagNameNS(namespace, dataTagName) | |
484 for name in names: | |
485 fn = getTextFromNode(name) | |
26 | 486 xmlFields.append({'name':sqlName(fn),'type':'text'}) |
14 | 487 |
26 | 488 if fieldsOnly: |
14 | 489 # return just field names |
26 | 490 return xmlFields |
14 | 491 |
492 # create table | |
28 | 493 if fields is None: |
31 | 494 fields = xmlFields |
495 | |
496 sqlFields = self.createEmptyTable(schema, table, fields) | |
16 | 497 numFields = len(sqlFields) |
15 | 498 fieldString = ", ".join(['"%s"'%f['name'] for f in sqlFields]) |
14 | 499 valString = ", ".join(["%s" for f in sqlFields]) |
16 | 500 sqlInsert = 'insert into "%s"."%s" (%s) values (%s)'%(schema,table,fieldString,valString) |
26 | 501 #logging.debug("importexcelsql: sqlInsert=%s"%sqlInsert) |
14 | 502 |
503 else: | |
504 # following rows are data | |
16 | 505 colNodes=node[1].getElementsByTagNameNS(namespace, colTagName) |
14 | 506 data = [] |
16 | 507 hasData = False |
508 for colNode in colNodes: | |
509 dataNodes=colNode.getElementsByTagNameNS(namespace, dataTagName) | |
510 if len(dataNodes) > 0: | |
511 val = getTextFromNode(dataNodes[0]) | |
512 hasData = True | |
513 else: | |
514 val = None | |
515 | |
14 | 516 data.append(val) |
517 | |
16 | 518 if not hasData: |
519 # ignore empty rows | |
520 continue | |
521 | |
522 # fix number of data fields | |
523 if len(data) > numFields: | |
524 del data[numFields:] | |
525 elif len(data) < numFields: | |
526 missFields = numFields - len(data) | |
527 data.extend(missFields * [None,]) | |
528 | |
529 logging.debug("importexcel sqlinsert=%s data=%s"%(sqlInsert,data)) | |
17 | 530 self.executeSQL(sqlInsert, data, hasResult=False) |
14 | 531 |
16 | 532 return cnt |
38 | 533 |
4
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
534 def manage_editRestDbInterface(self, title=None, connection_id=None, |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
535 REQUEST=None): |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
536 """Change the object""" |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
537 if title is not None: |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
538 self.title = title |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
539 |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
540 if connection_id is not None: |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
541 self.connection_id = connection_id |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
542 |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
543 #checkPermission=getSecurityManager().checkPermission |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
544 REQUEST.RESPONSE.redirect('manage_main') |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
545 |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
546 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
547 manage_addRestDbInterfaceForm=PageTemplateFile('zpt/addRestDbInterface',globals()) |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
548 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
549 def manage_addRestDbInterface(self, id, title='', label='', description='', |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
550 createPublic=0, |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
551 createUserF=0, |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
552 REQUEST=None): |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
553 """Add a new object with id *id*.""" |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
554 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
555 ob=RestDbInterface(str(id),title) |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
556 self._setObject(id, ob) |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
557 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
558 #checkPermission=getSecurityManager().checkPermission |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
559 REQUEST.RESPONSE.redirect('manage_main') |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
560 |
5 | 561 |