Mercurial > hg > ChinaGisRestApi
annotate RestDbInterface.py @ 277:9bfa7a6858f1
removed missing getFieldNames.
author | casties |
---|---|
date | Thu, 23 Feb 2012 21:37:37 +0100 |
parents | d1b43624cc63 |
children |
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 |
60 | 9 from AccessControl import getSecurityManager, Unauthorized |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
10 from Products.ZSQLExtend import ZSQLExtend |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
11 import logging |
15 | 12 import re |
18 | 13 import json |
19 | 14 import time |
70 | 15 import psycopg2 |
254
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
16 import urllib |
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
17 |
70 | 18 # make psycopg use unicode objects |
19 import psycopg2.extensions | |
20 psycopg2.extensions.register_type(psycopg2.extensions.UNICODE) | |
21 psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY) | |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
22 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
23 from zope.interface import implements |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
24 from zope.publisher.interfaces import IPublishTraverse |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
25 from ZPublisher.BaseRequest import DefaultPublishTraverse |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
26 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
27 |
70 | 28 def unicodify(s,alternate='latin-1'): |
29 """decode str (utf-8 or latin-1 representation) into unicode object""" | |
30 if not s: | |
31 return u"" | |
32 if isinstance(s, str): | |
33 try: | |
34 return s.decode('utf-8') | |
35 except: | |
36 return s.decode(alternate) | |
37 else: | |
38 return s | |
39 | |
40 def utf8ify(s): | |
41 """encode unicode object or string into byte string in utf-8 representation. | |
42 assumes string objects to be utf-8""" | |
43 if not s: | |
44 return "" | |
45 if isinstance(s, str): | |
46 return s | |
47 else: | |
48 return s.encode('utf-8') | |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
49 |
16 | 50 def getTextFromNode(node): |
14 | 51 """get the cdata content of a XML node""" |
16 | 52 if node is None: |
14 | 53 return "" |
16 | 54 |
55 if isinstance(node, list): | |
56 nodelist = node | |
57 else: | |
58 nodelist=node.childNodes | |
59 | |
14 | 60 rc = "" |
61 for node in nodelist: | |
62 if node.nodeType == node.TEXT_NODE: | |
63 rc = rc + node.data | |
64 return rc | |
65 | |
16 | 66 def sqlName(s,lc=True): |
67 """returns restricted ASCII-only version of string""" | |
15 | 68 if s is None: |
69 return "" | |
70 | |
71 # all else -> "_" | |
16 | 72 s = re.sub(r'[^A-Za-z0-9_]','_',s) |
15 | 73 if lc: |
74 return s.lower() | |
75 | |
76 return s | |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
77 |
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 class RestDbInterface(Folder): |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
80 """Object for RESTful database queries |
7 | 81 path schema: /db/{schema}/{table}/ |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
82 omitting table gives a list of schemas |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
83 omitting table and schema gives a list of schemas |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
84 """ |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
85 implements(IPublishTraverse) |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
86 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
87 meta_type="RESTdb" |
4
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
88 manage_options=Folder.manage_options+( |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
89 {'label':'Config','action':'manage_editRestDbInterfaceForm'}, |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
90 ) |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
91 |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
92 # management templates |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
93 manage_editRestDbInterfaceForm=PageTemplateFile('zpt/editRestDbInterface',globals()) |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
94 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
95 # data templates |
8 | 96 XML_index = PageTemplateFile('zpt/XML_index', globals()) |
97 XML_schema = PageTemplateFile('zpt/XML_schema', globals()) | |
98 XML_schema_table = PageTemplateFile('zpt/XML_schema_table', globals()) | |
99 HTML_index = PageTemplateFile('zpt/HTML_index', globals()) | |
100 HTML_schema = PageTemplateFile('zpt/HTML_schema', globals()) | |
101 HTML_schema_table = PageTemplateFile('zpt/HTML_schema_table', globals()) | |
254
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
102 GIS_schema_table = PageTemplateFile('zpt/GIS_schema_table', globals()) |
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
103 KML_schema_table = PageTemplateFile('zpt/KML_schema_table', globals()) |
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
104 HTML_schema_usertables = PageTemplateFile('zpt/HTML_schema_usertables', globals()) |
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
105 |
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
106 |
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
107 |
22 | 108 JSONHTML_index = PageTemplateFile('zpt/JSONHTML_index', globals()) |
109 JSONHTML_schema = PageTemplateFile('zpt/JSONHTML_schema', globals()) | |
110 JSONHTML_schema_table = PageTemplateFile('zpt/JSONHTML_schema_table', globals()) | |
24 | 111 # JSON_* templates are scripts |
254
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
112 |
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
113 |
45 | 114 def JSON_index(self): |
30 | 115 """JSON index function""" |
116 self.REQUEST.RESPONSE.setHeader("Content-Type", "application/json") | |
45 | 117 json.dump(self.getListOfSchemas(), self.REQUEST.RESPONSE) |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
118 |
45 | 119 def JSON_schema(self,schema): |
30 | 120 """JSON index function""" |
121 self.REQUEST.RESPONSE.setHeader("Content-Type", "application/json") | |
45 | 122 json.dump(self.getListOfTables(schema), self.REQUEST.RESPONSE) |
30 | 123 |
44 | 124 def JSON_schema_table(self,schema,table): |
30 | 125 """JSON index function""" |
273 | 126 logging.debug("start: json_schema") |
30 | 127 self.REQUEST.RESPONSE.setHeader("Content-Type", "application/json") |
44 | 128 json.dump(self.getTable(schema, table), self.REQUEST.RESPONSE) |
273 | 129 logging.debug("end: json_schema") |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
130 |
4
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
131 def __init__(self, id, title, connection_id=None): |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
132 """init""" |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
133 self.id = id |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
134 self.title = title |
4
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
135 # database connection id |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
136 self.connection_id = connection_id |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
137 # create template folder |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
138 self.manage_addFolder('template') |
44 | 139 |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
140 |
44 | 141 def getRestDbUrl(self): |
142 """returns url to the RestDb instance""" | |
143 return self.absolute_url() | |
144 | |
22 | 145 def getJsonString(self,object): |
146 """returns a JSON formatted string from object""" | |
147 return json.dumps(object) | |
4
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
148 |
17 | 149 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
|
150 """returns fresh DB cursor""" |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
151 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
|
152 if conn is None: |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
153 # create a new connection object |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
154 try: |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
155 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
|
156 # 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
|
157 connids = SQLConnectionIDs(self) |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
158 if len(connids) > 0: |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
159 connection_id = connids[0][0] |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
160 self.connection_id = connection_id |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
161 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
|
162 |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
163 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
|
164 da.connect('') |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
165 # 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
|
166 conn = da._v_database_connection |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
167 #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
|
168 self._v_database_connection = conn |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
169 except Exception, e: |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
170 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
|
171 |
5 | 172 cursor = conn.getcursor() |
17 | 173 if autocommit: |
174 # is there a better version to get to the connection? | |
175 cursor.connection.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) | |
176 | |
4
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
177 return cursor |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
178 |
55 | 179 def getFieldNameMap(self,fields): |
180 """returns a dict mapping field names to row indexes""" | |
181 map = {} | |
182 i = 0 | |
183 for f in fields: | |
184 map[f[0]] = i | |
185 i += 1 | |
186 | |
187 return map | |
188 | |
273 | 189 def getFieldNames(self,fields): |
190 """returns a dict mapping field names to row indexes""" | |
191 map = [] | |
192 i = 0 | |
193 for f in fields: | |
194 map.append(f[0]) | |
195 | |
196 | |
197 return map | |
198 | |
17 | 199 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
|
200 """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
|
201 result format: {"fields":fields, "rows":data}""" |
16 | 202 logging.debug("executeSQL query=%s args=%s"%(query,args)) |
17 | 203 cur = self.getCursor(autocommit=autocommit) |
53 | 204 if args is not None: |
205 # make sure args is a list | |
206 if isinstance(args,basestring): | |
207 args = (args,) | |
208 | |
4
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
209 cur.execute(query, args) |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
210 # description of returned fields |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
211 fields = cur.description |
17 | 212 if hasResult: |
213 # get all data in an array | |
214 data = cur.fetchall() | |
215 cur.close() | |
55 | 216 #logging.debug("fields: %s"%repr(fields)) |
58 | 217 #logging.debug("rows: %s"%repr(data)) |
17 | 218 return {"fields":fields, "rows":data} |
219 else: | |
220 cur.close() | |
221 return None | |
16 | 222 |
60 | 223 def isAllowed(self,action,schema,table,user=None): |
224 """returns if the requested action on the table is allowed""" | |
225 if user is None: | |
226 user = self.REQUEST.get('AUTHENTICATED_USER',None) | |
227 logging.debug("isAllowed action=%s schema=%s table=%s user=%s"%(action,schema,table,user)) | |
228 # no default policy! | |
229 return True | |
230 | |
231 | |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
232 def publishTraverse(self,request,name): |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
233 """change the traversal""" |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
234 # get stored path |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
235 path = request.get('restdb_path', []) |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
236 logging.debug("publishtraverse: name=%s restdb_path=%s"%(name,path)) |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
237 |
13 | 238 if name in ("index_html", "PUT"): |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
239 # end of traversal |
13 | 240 if request.get("method") == "POST" and request.get("action",None) == "PUT": |
241 # fake PUT by POST with action=PUT | |
242 name = "PUT" | |
243 | |
244 return getattr(self, name) | |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
245 #TODO: should we check more? |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
246 else: |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
247 # traverse |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
248 if len(path) == 0: |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
249 # first segment |
8 | 250 if name == 'db': |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
251 # virtual path -- continue traversing |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
252 path = [name] |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
253 request['restdb_path'] = path |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
254 else: |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
255 # try real path |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
256 tr = DefaultPublishTraverse(self, request) |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
257 ob = tr.publishTraverse(request, name) |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
258 return ob |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
259 else: |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
260 path.append(name) |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
261 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
262 # continue traversing |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
263 return self |
44 | 264 |
265 | |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
266 def index_html(self,REQUEST,RESPONSE): |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
267 """index method""" |
8 | 268 # ReST path was stored in request |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
269 path = REQUEST.get('restdb_path',[]) |
19 | 270 |
8 | 271 # type and format are real parameter |
26 | 272 resultFormat = REQUEST.get('format','HTML').upper() |
27 | 273 queryType = REQUEST.get('type',None) |
273 | 274 from_year_name = REQUEST.get('from_year_name',None) |
275 until_year_name = REQUEST.get('until_year_name',None) | |
19 | 276 |
26 | 277 logging.debug("index_html path=%s resultFormat=%s queryType=%s"%(path,resultFormat,queryType)) |
8 | 278 |
26 | 279 if queryType is not None: |
280 # non-empty queryType -- look for template | |
281 pt = getattr(self.template, "%s_%s"%(resultFormat,queryType), None) | |
8 | 282 if pt is not None: |
273 | 283 return pt(format=resultFormat,type=queryType,path=path,from_year_name=from_year_name,until_year_name=until_year_name) |
8 | 284 |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
285 if len(path) == 1: |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
286 # list of schemas |
61 | 287 return self.showListOfSchemas(format=resultFormat) |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
288 elif len(path) == 2: |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
289 # list of tables |
61 | 290 return self.showListOfTables(format=resultFormat,schema=path[1]) |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
291 elif len(path) == 3: |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
292 # table |
25 | 293 if REQUEST.get("method") == "POST" and REQUEST.get("create_table_file",None) is not None: |
24 | 294 # POST to table to check |
61 | 295 return self.checkTable(format=resultFormat,schema=path[1],table=path[2]) |
24 | 296 # else show table |
273 | 297 logging.debug("index_html:will showTable") |
298 x= self.showTable(format=resultFormat,schema=path[1],table=path[2],REQUEST=REQUEST, RESPONSE=RESPONSE) | |
299 logging.debug("index_html:have done showTable") | |
300 return x | |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
301 # don't know what to do |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
302 return str(REQUEST) |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
303 |
12 | 304 def PUT(self, REQUEST, RESPONSE): |
305 """ | |
306 Implement WebDAV/HTTP PUT/FTP put method for this object. | |
307 """ | |
13 | 308 logging.debug("RestDbInterface PUT") |
309 #logging.debug("req=%s"%REQUEST) | |
12 | 310 #self.dav__init(REQUEST, RESPONSE) |
311 #self.dav__simpleifhandler(REQUEST, RESPONSE) | |
13 | 312 # ReST path was stored in request |
313 path = REQUEST.get('restdb_path',[]) | |
314 if len(path) == 3: | |
315 schema = path[1] | |
316 tablename = path[2] | |
317 file = REQUEST.get("create_table_file",None) | |
318 if file is None: | |
319 RESPONSE.setStatus(400) | |
320 return | |
4
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
321 |
30 | 322 fields = None |
323 fieldsStr = REQUEST.get("create_table_fields",None) | |
324 logging.debug("put with schema=%s table=%s file=%s fields=%s"%(schema,tablename,file,repr(fieldsStr))) | |
325 if fieldsStr is not None: | |
326 # unpack fields | |
327 fields = [{"name":n, "type": t} for (n,t) in [f.split(":") for f in fieldsStr.split(",")]] | |
31 | 328 |
28 | 329 ret = self.createTableFromXML(schema, tablename, file, fields) |
26 | 330 # return the result as JSON |
331 format = REQUEST.get("format","JSON") | |
332 if format == "JSON": | |
20 | 333 RESPONSE.setHeader("Content-Type", "application/json") |
334 json.dump(ret, RESPONSE) | |
26 | 335 |
336 elif format == "JSONHTML": | |
20 | 337 RESPONSE.setHeader("Content-Type", "text/html") |
338 RESPONSE.write("<html>\n<body>\n<pre>") | |
339 json.dump(ret, RESPONSE) | |
340 RESPONSE.write("</pre>\n</body>\n</html>") | |
13 | 341 |
342 else: | |
343 # 400 Bad Request | |
344 RESPONSE.setStatus(400) | |
345 return | |
252
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
346 def getAttributeNames(self,schema='public',table=None): |
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
347 return self.executeSQL("SELECT attname FROM pg_attribute, pg_class WHERE pg_class.oid = attrelid AND attnum>0 AND relname = '%s';"%(table)) |
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
348 |
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
349 def getAttributeTypes(self,schema='public',table=None): |
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
350 return self.executeSQL("SELECT field_name, gis_type FROM public.gis_table_meta_rows WHERE table_name = '%s';"%(table)) |
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
351 |
61 | 352 def showTable(self,format='XML',schema='public',table=None,REQUEST=None,RESPONSE=None): |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
353 """returns PageTemplate with tables""" |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
354 logging.debug("showtable") |
38 | 355 if REQUEST is None: |
356 REQUEST = self.REQUEST | |
254
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
357 queryArgs={'doc':None,'id':None} |
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
358 queryArgs['doc'] = REQUEST.get('doc') |
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
359 queryArgs['id'] = REQUEST.get('id') |
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
360 |
23 | 361 # should be cross-site accessible |
25 | 362 if RESPONSE is None: |
363 RESPONSE = self.REQUEST.RESPONSE | |
38 | 364 |
23 | 365 RESPONSE.setHeader('Access-Control-Allow-Origin', '*') |
38 | 366 |
22 | 367 # everything else has its own template |
254
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
368 pt = getattr(self.template, '%s_schema_table'%format, REQUEST) |
273 | 369 logging.debug("showtable: gottemplate") |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
370 if pt is None: |
254
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
371 return "ERROR!! template %s_schema_table not found at %s"%(format, self.template ) |
44 | 372 #data = self.getTable(schema,table) |
273 | 373 logging.debug("table:"+repr(table)) |
374 #x = pt(schema=schema,table=table,args={}) | |
375 x = pt(schema=schema,table=table,args=queryArgs) | |
376 logging.debug("showtable: executed Table") | |
377 return x | |
254
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
378 |
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
379 def getLiveUrl(self,schema,table,useTimestamp=True,REQUEST=None): |
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
380 if REQUEST is None: |
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
381 REQUEST = self.REQUEST |
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
382 logging.debug("getLiveUrl") |
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
383 baseUrl = self.absolute_url() |
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
384 timestamp = time.time() |
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
385 # filter parameters in URL and add to new URL |
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
386 params = [p for p in REQUEST.form.items() if p[0] not in ('format','timestamp')] |
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
387 params.append(('format','KML')) |
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
388 if useTimestamp: |
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
389 # add timestamp so URL changes every time |
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
390 params.append(('timestamp',timestamp)) |
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
391 paramstr = urllib.urlencode(params) |
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
392 return "%s/db/%s/%s?%s"%(baseUrl,schema,table,paramstr) |
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
393 |
901c1f745d13
GIS-Links from MPDL-Documents now served by Mappit-Server
fknauft
parents:
252
diff
changeset
|
394 |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
395 |
58 | 396 def getTable(self,schema='public',table=None,sortBy=1,username='guest'): |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
397 """return table data""" |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
398 logging.debug("gettable") |
252
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
399 attrNames=self.getAttributeNames(schema,table) |
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
400 attrTypes=self.getAttributeTypes(schema,table) |
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
401 attrString="" |
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
402 # try: |
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
403 for name in attrNames['rows']: |
273 | 404 logging.debug("name: "+repr( name[0])) |
252
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
405 not_added=True |
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
406 if name[0] == "the_geom": #FJK: the table column is "the_geom" |
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
407 attrString=attrString+"ST_AsText("+name[0]+")," |
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
408 not_added=False |
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
409 break |
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
410 for a_iter in attrTypes['rows']: |
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
411 not_added = True |
273 | 412 logging.debug("attrTypes.field_name: "+ repr(a_iter[0])) |
252
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
413 if a_iter[0]==name[0]: |
273 | 414 logging.debug("attrTypes.gis_type: "+ repr(a_iter[1])) |
252
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
415 if a_iter[1] == "the_geom": #FJK: the table column is registered in gis_table_meta_rows as type "the_geom" |
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
416 attrString=attrString+"ST_AsText("+name[0]+")," |
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
417 not_added=False |
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
418 if not_added: |
264 | 419 if name[0].find('pg.dropped')==-1: |
420 attrString=attrString+name[0]+"," | |
252
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
421 attrString=str(attrString).rsplit(",",1)[0] #to remove last "," |
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
422 if sortBy: |
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
423 data = self.executeSQL('select %s from "%s"."%s" order by %s'%(attrString,schema,table,sortBy)) |
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
424 else: |
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
425 data = self.executeSQL('select %s from "%s"."%s"'%(attrString,schema,table)) |
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
426 # except: |
227 | 427 """ table does not exist """ |
252
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
428 # fields=self.get |
efd2469d1722
geometry-column of tables will be displayed as string
fknauft
parents:
230
diff
changeset
|
429 # self.createEmptyTable(schema, table, fields) |
273 | 430 logging.debug("getTable: done") |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
431 return data |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
432 |
26 | 433 def hasTable(self,schema='public',table=None,username='guest'): |
434 """return if table exists""" | |
435 logging.debug("hastable") | |
436 data = self.executeSQL('select 1 from information_schema.tables where table_schema=%s and table_name=%s',(schema,table)) | |
437 ret = bool(data['rows']) | |
438 return ret | |
439 | |
61 | 440 def showListOfTables(self,format='XML',schema='public',REQUEST=None,RESPONSE=None): |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
441 """returns PageTemplate with list of tables""" |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
442 logging.debug("showlistoftables") |
23 | 443 # should be cross-site accessible |
25 | 444 if RESPONSE is None: |
445 RESPONSE = self.REQUEST.RESPONSE | |
23 | 446 RESPONSE.setHeader('Access-Control-Allow-Origin', '*') |
24 | 447 |
9 | 448 pt = getattr(self.template, '%s_schema'%format, None) |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
449 if pt is None: |
9 | 450 return "ERROR!! template %s_schema not found"%format |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
451 |
45 | 452 #data = self.getListOfTables(schema) |
453 return pt(schema=schema) | |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
454 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
455 def getListOfTables(self,schema='public',username='guest'): |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
456 """return list of tables""" |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
457 logging.debug("getlistoftables") |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
458 # get list of fields and types of db table |
61 | 459 #qstr="""SELECT c.relname AS tablename FROM pg_catalog.pg_class c |
460 # LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace | |
461 # WHERE c.relkind IN ('r','') AND n.nspname NOT IN ('pg_catalog', 'pg_toast') | |
462 # AND pg_catalog.pg_table_is_visible(c.oid) | |
463 # AND c.relname ORDER BY 1""" | |
464 qstr = """SELECT table_name FROM information_schema.tables WHERE table_type = 'BASE TABLE' | |
465 AND table_schema = %s ORDER BY 1""" | |
466 data=self.executeSQL(qstr,(schema,)) | |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
467 return data |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
468 |
61 | 469 def showListOfSchemas(self,format='XML',REQUEST=None,RESPONSE=None): |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
470 """returns PageTemplate with list of schemas""" |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
471 logging.debug("showlistofschemas") |
23 | 472 # should be cross-site accessible |
25 | 473 if RESPONSE is None: |
474 RESPONSE = self.REQUEST.RESPONSE | |
23 | 475 RESPONSE.setHeader('Access-Control-Allow-Origin', '*') |
24 | 476 |
9 | 477 pt = getattr(self.template, '%s_index'%format, None) |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
478 if pt is None: |
9 | 479 return "ERROR!! template %s_index not found"%format |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
480 |
45 | 481 #data = self.getListOfSchemas() |
482 return pt() | |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
483 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
484 def getListOfSchemas(self,username='guest'): |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
485 """return list of schemas""" |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
486 logging.debug("getlistofschemas") |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
487 # TODO: really look up schemas |
9 | 488 data={'fields': (('schemas',),), 'rows': [('public',),]} |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
489 return data |
26 | 490 |
61 | 491 def checkTable(self,format,schema,table,REQUEST=None,RESPONSE=None): |
26 | 492 """check the table. |
493 returns valid data fields and table name.""" | |
494 if REQUEST is None: | |
495 REQUEST = self.REQUEST | |
496 RESPONSE = REQUEST.RESPONSE | |
74 | 497 |
26 | 498 file = REQUEST.get("create_table_file",None) |
499 res = self.checkTableFromXML(schema, table, file) | |
500 logging.debug("checkTable result=%s"%repr(res)) | |
501 # return the result as JSON | |
61 | 502 if format == "JSON": |
26 | 503 RESPONSE.setHeader("Content-Type", "application/json") |
504 json.dump(res, RESPONSE) | |
505 | |
61 | 506 elif format == "JSONHTML": |
26 | 507 RESPONSE.setHeader("Content-Type", "text/html") |
508 RESPONSE.write("<html>\n<body>\n<pre>") | |
509 json.dump(res, RESPONSE) | |
510 RESPONSE.write("</pre>\n</body>\n</html>") | |
511 | |
512 else: | |
61 | 513 return "ERROR: invalid format" |
74 | 514 |
26 | 515 def checkTableFromXML(self,schema,table,data,REQUEST=None,RESPONSE=None): |
516 """check the table with the given XML data. | |
517 returns valid data fields and table name.""" | |
518 logging.debug("checkTableFromXML schema=%s table=%s"%(schema,table)) | |
519 # clean table name | |
520 tablename = sqlName(table) | |
521 tableExists = self.hasTable(schema, table) | |
522 if data is None: | |
523 fieldNames = [] | |
524 else: | |
525 # get list of field names from upload file | |
526 fields = self.importExcelXML(schema,tablename,data,fieldsOnly=True) | |
14 | 527 |
26 | 528 res = {'tablename': tablename, 'table_exists': tableExists} |
529 res['fields'] = fields | |
530 return res | |
19 | 531 |
14 | 532 def createEmptyTable(self,schema,table,fields): |
533 """create a table with the given fields | |
534 returns list of created fields""" | |
15 | 535 logging.debug("createEmptyTable") |
19 | 536 |
14 | 537 sqlFields = [] |
538 for f in fields: | |
539 if isinstance(f,dict): | |
540 # {name: XX, type: YY} | |
541 name = sqlName(f['name']) | |
542 type = f['type'] | |
70 | 543 if hasattr(self, 'toSqlTypeMap'): |
544 sqltype = self.toSqlTypeMap[type] | |
545 else: | |
546 sqltype = 'text' | |
14 | 547 |
548 else: | |
549 # name only | |
550 name = sqlName(f) | |
551 type = 'text' | |
31 | 552 sqltype = 'text' |
14 | 553 |
31 | 554 sqlFields.append({'name':name, 'type':type, 'sqltype':sqltype}) |
14 | 555 |
60 | 556 if self.hasTable(schema,table): |
557 # TODO: find owner | |
558 if not self.isAllowed("update", schema, table): | |
559 raise Unauthorized | |
560 self.executeSQL('drop table "%s"."%s"'%(schema,table),hasResult=False) | |
561 else: | |
562 if not self.isAllowed("create", schema, table): | |
563 raise Unauthorized | |
564 | |
43 | 565 fieldString = ", ".join(['"%s" %s'%(f['name'],f['sqltype']) for f in sqlFields]) |
566 sqlString = 'create table "%s"."%s" (%s)'%(schema,table,fieldString) | |
567 logging.debug("createemptytable: SQL=%s"%sqlString) | |
568 self.executeSQL(sqlString,hasResult=False) | |
569 self.setTableMetaTypes(schema,table,sqlFields) | |
570 return sqlFields | |
19 | 571 |
28 | 572 def createTableFromXML(self,schema,table,data, fields=None): |
13 | 573 """create or replace a table with the given XML data""" |
28 | 574 logging.debug("createTableFromXML schema=%s table=%s data=%s fields=%s"%(schema,table,data,fields)) |
17 | 575 tablename = sqlName(table) |
28 | 576 self.importExcelXML(schema, tablename, data, fields) |
17 | 577 return {"tablename": tablename} |
76 | 578 |
28 | 579 def importExcelXML(self,schema,table,xmldata,fields=None,fieldsOnly=False): |
14 | 580 ''' |
581 Import XML file in Excel format into the table | |
582 @param table: name of the table the xml shall be imported into | |
583 ''' | |
584 from xml.dom.pulldom import parseString,parse | |
585 | |
60 | 586 if not (fieldsOnly or self.isAllowed("create", schema, table)): |
587 raise Unauthorized | |
588 | |
14 | 589 namespace = "urn:schemas-microsoft-com:office:spreadsheet" |
590 containerTagName = "Table" | |
591 rowTagName = "Row" | |
16 | 592 colTagName = "Cell" |
14 | 593 dataTagName = "Data" |
26 | 594 xmlFields = [] |
14 | 595 sqlFields = [] |
16 | 596 numFields = 0 |
14 | 597 sqlInsert = None |
598 | |
599 logging.debug("import excel xml") | |
76 | 600 |
14 | 601 ret="" |
16 | 602 if isinstance(xmldata, str): |
14 | 603 logging.debug("importXML reading string data") |
16 | 604 doc=parseString(xmldata) |
73 | 605 else: |
14 | 606 logging.debug("importXML reading file data") |
16 | 607 doc=parse(xmldata) |
14 | 608 |
609 cnt = 0 | |
610 while True: | |
611 node=doc.getEvent() | |
16 | 612 |
14 | 613 if node is None: |
614 break | |
615 | |
616 else: | |
16 | 617 #logging.debug("tag=%s"%node[1].localName) |
14 | 618 if node[1].localName is not None: |
619 tagName = node[1].localName.lower() | |
76 | 620 else: |
14 | 621 # ignore non-tag nodes |
622 continue | |
16 | 623 |
14 | 624 if tagName == rowTagName.lower(): |
625 # start of row | |
626 doc.expandNode(node[1]) | |
627 cnt += 1 | |
628 if cnt == 1: | |
629 # first row -- field names | |
630 names=node[1].getElementsByTagNameNS(namespace, dataTagName) | |
631 for name in names: | |
632 fn = getTextFromNode(name) | |
26 | 633 xmlFields.append({'name':sqlName(fn),'type':'text'}) |
14 | 634 |
26 | 635 if fieldsOnly: |
14 | 636 # return just field names |
26 | 637 return xmlFields |
14 | 638 |
639 # create table | |
28 | 640 if fields is None: |
31 | 641 fields = xmlFields |
642 | |
643 sqlFields = self.createEmptyTable(schema, table, fields) | |
16 | 644 numFields = len(sqlFields) |
15 | 645 fieldString = ", ".join(['"%s"'%f['name'] for f in sqlFields]) |
14 | 646 valString = ", ".join(["%s" for f in sqlFields]) |
16 | 647 sqlInsert = 'insert into "%s"."%s" (%s) values (%s)'%(schema,table,fieldString,valString) |
26 | 648 #logging.debug("importexcelsql: sqlInsert=%s"%sqlInsert) |
14 | 649 |
650 else: | |
651 # following rows are data | |
16 | 652 colNodes=node[1].getElementsByTagNameNS(namespace, colTagName) |
14 | 653 data = [] |
16 | 654 hasData = False |
227 | 655 lineIndex=0 |
16 | 656 for colNode in colNodes: |
227 | 657 lineIndex+=1 |
16 | 658 dataNodes=colNode.getElementsByTagNameNS(namespace, dataTagName) |
659 if len(dataNodes) > 0: | |
227 | 660 dataIndex=0 |
228 | 661 if colNode.hasAttribute(u'ss:Index'): |
230 | 662 dataIndex=int(colNode.getAttribute(u'ss:Index')) |
663 while dataIndex>lineIndex: | |
228 | 664 data.append(None) |
230 | 665 lineIndex+=1 |
666 else: | |
667 val = getTextFromNode(dataNodes[0]) | |
668 hasData = True | |
16 | 669 else: |
670 val = None | |
19 | 671 |
263 | 672 if val!=None: |
673 a=val.rfind('.0') | |
674 b=len(val) | |
675 if a==b-2: | |
676 val=val.rpartition('.')[0] | |
14 | 677 data.append(val) |
678 | |
16 | 679 if not hasData: |
680 # ignore empty rows | |
681 continue | |
682 | |
683 # fix number of data fields | |
684 if len(data) > numFields: | |
685 del data[numFields:] | |
686 elif len(data) < numFields: | |
687 missFields = numFields - len(data) | |
688 data.extend(missFields * [None,]) | |
689 | |
690 logging.debug("importexcel sqlinsert=%s data=%s"%(sqlInsert,data)) | |
17 | 691 self.executeSQL(sqlInsert, data, hasResult=False) |
14 | 692 |
16 | 693 return cnt |
38 | 694 |
4
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
695 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
|
696 REQUEST=None): |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
697 """Change the object""" |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
698 if title is not None: |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
699 self.title = title |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
700 |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
701 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
|
702 self.connection_id = connection_id |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
703 |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
704 #checkPermission=getSecurityManager().checkPermission |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
705 REQUEST.RESPONSE.redirect('manage_main') |
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
706 |
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
707 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
708 manage_addRestDbInterfaceForm=PageTemplateFile('zpt/addRestDbInterface',globals()) |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
709 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
710 def manage_addRestDbInterface(self, id, title='', label='', description='', |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
711 createPublic=0, |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
712 createUserF=0, |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
713 REQUEST=None): |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
714 """Add a new object with id *id*.""" |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
715 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
716 ob=RestDbInterface(str(id),title) |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
717 self._setObject(id, ob) |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
718 |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
719 #checkPermission=getSecurityManager().checkPermission |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
720 REQUEST.RESPONSE.redirect('manage_main') |
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
721 |
5 | 722 |