Mercurial > hg > ChinaGisRestApi
annotate RestDbInterface.py @ 33:355b1fa2d78f
added meta permissions check
| author | casties |
|---|---|
| date | Tue, 31 Aug 2010 14:20:24 +0200 |
| parents | c732c2ff61d9 |
| children | c237699c4752 |
| 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 |
| 19 | 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 |
| 33 | 167 def checkTableMetaPermission(self,action,schema,table,user=None): |
| 168 """returns if the requested action on the table is allowed""" | |
| 169 logging.debug("checktablemetapermissions action=%s schema=%s table=%s user=%s"%(action,schema,table,user)) | |
| 170 if user is None: | |
| 171 user = self.REQUEST.get('AUTHENTICATED_USER',None) | |
| 172 logging.debug("user=%s"%user) | |
| 173 # TODO: what now? | |
| 174 return True | |
| 175 | |
| 31 | 176 def setTableMetaTypes(self,schema,table,fields): |
| 177 """sets the GIS meta information for table""" | |
| 178 logging.debug("settablemetatypes schema=%s, table=%s, fields=%s"%(schema,table,fields)) | |
| 179 # TODO: what now? | |
|
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
180 |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
181 def publishTraverse(self,request,name): |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
182 """change the traversal""" |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
183 # get stored path |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
184 path = request.get('restdb_path', []) |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
185 logging.debug("publishtraverse: name=%s restdb_path=%s"%(name,path)) |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
186 |
| 13 | 187 if name in ("index_html", "PUT"): |
|
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
188 # end of traversal |
| 13 | 189 if request.get("method") == "POST" and request.get("action",None) == "PUT": |
| 190 # fake PUT by POST with action=PUT | |
| 191 name = "PUT" | |
| 192 | |
| 193 return getattr(self, name) | |
|
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
194 #TODO: should we check more? |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
195 else: |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
196 # traverse |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
197 if len(path) == 0: |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
198 # first segment |
| 8 | 199 if name == 'db': |
|
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
200 # virtual path -- continue traversing |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
201 path = [name] |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
202 request['restdb_path'] = path |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
203 else: |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
204 # try real path |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
205 tr = DefaultPublishTraverse(self, request) |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
206 ob = tr.publishTraverse(request, name) |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
207 return ob |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
208 else: |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
209 path.append(name) |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
210 |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
211 # continue traversing |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
212 return self |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
213 |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
214 def index_html(self,REQUEST,RESPONSE): |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
215 """index method""" |
| 8 | 216 # ReST path was stored in request |
|
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
217 path = REQUEST.get('restdb_path',[]) |
| 19 | 218 |
| 27 | 219 # type and format are real parameter |
| 26 | 220 resultFormat = REQUEST.get('format','HTML').upper() |
| 27 | 221 queryType = REQUEST.get('type',None) |
| 19 | 222 |
| 26 | 223 logging.debug("index_html path=%s resultFormat=%s queryType=%s"%(path,resultFormat,queryType)) |
| 8 | 224 |
| 26 | 225 if queryType is not None: |
| 226 # non-empty queryType -- look for template | |
| 227 pt = getattr(self.template, "%s_%s"%(resultFormat,queryType), None) | |
| 8 | 228 if pt is not None: |
| 26 | 229 return pt(format=resultFormat,type=queryType,path=path) |
| 8 | 230 |
|
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
231 if len(path) == 1: |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
232 # list of schemas |
| 26 | 233 return self.showListOfSchemas(resultFormat=resultFormat) |
|
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
234 elif len(path) == 2: |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
235 # list of tables |
| 26 | 236 return self.showListOfTables(resultFormat=resultFormat,schema=path[1]) |
|
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
237 elif len(path) == 3: |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
238 # table |
| 25 | 239 if REQUEST.get("method") == "POST" and REQUEST.get("create_table_file",None) is not None: |
| 24 | 240 # POST to table to check |
| 26 | 241 return self.checkTable(resultFormat=resultFormat,schema=path[1],table=path[2]) |
| 24 | 242 # else show table |
| 26 | 243 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
|
244 |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
245 # don't know what to do |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
246 return str(REQUEST) |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
247 |
| 12 | 248 def PUT(self, REQUEST, RESPONSE): |
| 249 """ | |
| 250 Implement WebDAV/HTTP PUT/FTP put method for this object. | |
| 251 """ | |
| 13 | 252 logging.debug("RestDbInterface PUT") |
| 253 #logging.debug("req=%s"%REQUEST) | |
| 12 | 254 #self.dav__init(REQUEST, RESPONSE) |
| 255 #self.dav__simpleifhandler(REQUEST, RESPONSE) | |
| 13 | 256 # ReST path was stored in request |
| 257 path = REQUEST.get('restdb_path',[]) | |
| 258 if len(path) == 3: | |
| 259 schema = path[1] | |
| 260 tablename = path[2] | |
| 261 file = REQUEST.get("create_table_file",None) | |
| 262 if file is None: | |
| 263 RESPONSE.setStatus(400) | |
| 264 return | |
| 265 | |
| 30 | 266 fields = None |
| 267 fieldsStr = REQUEST.get("create_table_fields",None) | |
| 268 logging.debug("put with schema=%s table=%s file=%s fields=%s"%(schema,tablename,file,repr(fieldsStr))) | |
| 269 if fieldsStr is not None: | |
| 270 # unpack fields | |
| 271 fields = [{"name":n, "type": t} for (n,t) in [f.split(":") for f in fieldsStr.split(",")]] | |
| 31 | 272 |
| 28 | 273 ret = self.createTableFromXML(schema, tablename, file, fields) |
| 26 | 274 # return the result as JSON |
| 275 format = REQUEST.get("format","JSON") | |
| 276 if format == "JSON": | |
| 20 | 277 RESPONSE.setHeader("Content-Type", "application/json") |
| 278 json.dump(ret, RESPONSE) | |
| 26 | 279 |
| 280 elif format == "JSONHTML": | |
| 20 | 281 RESPONSE.setHeader("Content-Type", "text/html") |
| 282 RESPONSE.write("<html>\n<body>\n<pre>") | |
| 283 json.dump(ret, RESPONSE) | |
| 284 RESPONSE.write("</pre>\n</body>\n</html>") | |
| 13 | 285 |
| 286 else: | |
| 287 # 400 Bad Request | |
| 288 RESPONSE.setStatus(400) | |
| 289 return | |
| 12 | 290 |
| 26 | 291 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
|
292 """returns PageTemplate with tables""" |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
293 logging.debug("showtable") |
| 23 | 294 # should be cross-site accessible |
| 25 | 295 if RESPONSE is None: |
| 296 RESPONSE = self.REQUEST.RESPONSE | |
| 23 | 297 RESPONSE.setHeader('Access-Control-Allow-Origin', '*') |
| 22 | 298 # GIS gets special treatment |
| 26 | 299 if resultFormat=="GIS": |
| 23 | 300 id = REQUEST.get('id',[]) |
| 301 doc = REQUEST.get('doc',None) | |
| 22 | 302 return self.showGoogleMap(schema=path[1],table=path[2],id=id,doc=doc) |
| 303 | |
| 304 # everything else has its own template | |
| 26 | 305 pt = getattr(self.template, '%s_schema_table'%resultFormat, None) |
|
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
306 if pt is None: |
| 26 | 307 return "ERROR!! template %s_schema_table not found"%resultFormat |
|
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
308 |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
309 data = self.getTable(schema,table) |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
310 return pt(data=data,tablename=table) |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
311 |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
312 def getTable(self,schema='public',table=None,username='guest'): |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
313 """return table data""" |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
314 logging.debug("gettable") |
| 16 | 315 data = self.executeSQL('select * from "%s"."%s"'%(schema,table)) |
|
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
316 return data |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
317 |
| 26 | 318 def hasTable(self,schema='public',table=None,username='guest'): |
| 319 """return if table exists""" | |
| 320 logging.debug("hastable") | |
| 321 data = self.executeSQL('select 1 from information_schema.tables where table_schema=%s and table_name=%s',(schema,table)) | |
| 322 ret = bool(data['rows']) | |
| 323 return ret | |
| 324 | |
| 325 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
|
326 """returns PageTemplate with list of tables""" |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
327 logging.debug("showlistoftables") |
| 23 | 328 # should be cross-site accessible |
| 25 | 329 if RESPONSE is None: |
| 330 RESPONSE = self.REQUEST.RESPONSE | |
| 23 | 331 RESPONSE.setHeader('Access-Control-Allow-Origin', '*') |
| 24 | 332 |
| 26 | 333 pt = getattr(self.template, '%s_schema'%resultFormat, None) |
|
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
334 if pt is None: |
| 26 | 335 return "ERROR!! template %s_schema not found"%resultFormat |
|
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
336 |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
337 data = self.getListOfTables(schema) |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
338 return pt(data=data,schema=schema) |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
339 |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
340 def getListOfTables(self,schema='public',username='guest'): |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
341 """return list of tables""" |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
342 logging.debug("getlistoftables") |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
343 # get list of fields and types of db table |
| 22 | 344 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
|
345 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
|
346 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
|
347 AND pg_catalog.pg_table_is_visible(c.oid)""" |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
348 #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
|
349 data=self.executeSQL(qstr) |
|
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
350 return data |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
351 |
| 26 | 352 def showListOfSchemas(self,resultFormat='XML',REQUEST=None,RESPONSE=None): |
|
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
353 """returns PageTemplate with list of schemas""" |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
354 logging.debug("showlistofschemas") |
| 23 | 355 # should be cross-site accessible |
| 25 | 356 if RESPONSE is None: |
| 357 RESPONSE = self.REQUEST.RESPONSE | |
| 23 | 358 RESPONSE.setHeader('Access-Control-Allow-Origin', '*') |
| 24 | 359 |
| 26 | 360 pt = getattr(self.template, '%s_index'%resultFormat, None) |
|
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
361 if pt is None: |
| 26 | 362 return "ERROR!! template %s_index not found"%resultFormat |
|
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
363 |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
364 data = self.getListOfSchemas() |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
365 return pt(data=data) |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
366 |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
367 def getListOfSchemas(self,username='guest'): |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
368 """return list of schemas""" |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
369 logging.debug("getlistofschemas") |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
370 # TODO: really look up schemas |
| 9 | 371 data={'fields': (('schemas',),), 'rows': [('public',),]} |
|
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
372 return data |
| 14 | 373 |
| 26 | 374 def checkTable(self,resultFormat,schema,table,REQUEST=None,RESPONSE=None): |
| 375 """check the table. | |
| 376 returns valid data fields and table name.""" | |
| 377 if REQUEST is None: | |
| 378 REQUEST = self.REQUEST | |
| 379 RESPONSE = REQUEST.RESPONSE | |
| 380 | |
| 381 file = REQUEST.get("create_table_file",None) | |
| 382 res = self.checkTableFromXML(schema, table, file) | |
| 383 logging.debug("checkTable result=%s"%repr(res)) | |
| 384 # return the result as JSON | |
| 385 if resultFormat == "JSON": | |
| 386 RESPONSE.setHeader("Content-Type", "application/json") | |
| 387 json.dump(res, RESPONSE) | |
| 388 | |
| 389 elif resultFormat == "JSONHTML": | |
| 390 RESPONSE.setHeader("Content-Type", "text/html") | |
| 391 RESPONSE.write("<html>\n<body>\n<pre>") | |
| 392 json.dump(res, RESPONSE) | |
| 393 RESPONSE.write("</pre>\n</body>\n</html>") | |
| 394 | |
| 395 else: | |
| 396 return "ERROR: invalid resultFormat" | |
| 397 | |
| 398 def checkTableFromXML(self,schema,table,data,REQUEST=None,RESPONSE=None): | |
| 399 """check the table with the given XML data. | |
| 400 returns valid data fields and table name.""" | |
| 401 logging.debug("checkTableFromXML schema=%s table=%s"%(schema,table)) | |
| 402 # clean table name | |
| 403 tablename = sqlName(table) | |
| 404 tableExists = self.hasTable(schema, table) | |
| 405 if data is None: | |
| 406 fieldNames = [] | |
| 407 else: | |
| 408 # get list of field names from upload file | |
| 409 fields = self.importExcelXML(schema,tablename,data,fieldsOnly=True) | |
| 410 | |
| 411 res = {'tablename': tablename, 'table_exists': tableExists} | |
| 412 res['fields'] = fields | |
| 413 return res | |
| 414 | |
| 14 | 415 def createEmptyTable(self,schema,table,fields): |
| 416 """create a table with the given fields | |
| 417 returns list of created fields""" | |
| 15 | 418 logging.debug("createEmptyTable") |
| 14 | 419 sqlFields = [] |
| 420 for f in fields: | |
| 421 if isinstance(f,dict): | |
| 422 # {name: XX, type: YY} | |
| 423 name = sqlName(f['name']) | |
| 424 type = f['type'] | |
| 31 | 425 sqltype = gisToSqlTypeMap[type] |
| 14 | 426 |
| 427 else: | |
| 428 # name only | |
| 429 name = sqlName(f) | |
| 430 type = 'text' | |
| 31 | 431 sqltype = 'text' |
| 14 | 432 |
| 31 | 433 sqlFields.append({'name':name, 'type':type, 'sqltype':sqltype}) |
| 14 | 434 |
| 33 | 435 if self.checkTableMetaPermission("create", schema, table): |
| 436 self.executeSQL('drop table if exists "%s"."%s"'%(schema,table),hasResult=False) | |
| 437 fieldString = ", ".join(['"%s" %s'%(f['name'],f['sqltype']) for f in sqlFields]) | |
| 438 sqlString = 'create table "%s"."%s" (%s)'%(schema,table,fieldString) | |
| 439 logging.debug("createemptytable: SQL=%s"%sqlString) | |
| 440 self.executeSQL(sqlString,hasResult=False) | |
| 441 self.setTableMetaTypes(schema,table,sqlFields) | |
| 442 return sqlFields | |
| 443 else: | |
| 444 logging.warning("create table not allowed!") | |
| 445 # throw exception? | |
| 446 return None | |
| 26 | 447 |
| 28 | 448 def createTableFromXML(self,schema,table,data, fields=None): |
| 13 | 449 """create or replace a table with the given XML data""" |
| 28 | 450 logging.debug("createTableFromXML schema=%s table=%s data=%s fields=%s"%(schema,table,data,fields)) |
| 17 | 451 tablename = sqlName(table) |
| 28 | 452 self.importExcelXML(schema, tablename, data, fields) |
| 17 | 453 return {"tablename": tablename} |
| 14 | 454 |
| 28 | 455 def importExcelXML(self,schema,table,xmldata,fields=None,fieldsOnly=False): |
| 14 | 456 ''' |
| 457 Import XML file in Excel format into the table | |
| 458 @param table: name of the table the xml shall be imported into | |
| 459 ''' | |
| 460 from xml.dom.pulldom import parseString,parse | |
| 461 | |
| 462 namespace = "urn:schemas-microsoft-com:office:spreadsheet" | |
| 463 containerTagName = "Table" | |
| 464 rowTagName = "Row" | |
| 16 | 465 colTagName = "Cell" |
| 14 | 466 dataTagName = "Data" |
| 26 | 467 xmlFields = [] |
| 14 | 468 sqlFields = [] |
| 16 | 469 numFields = 0 |
| 14 | 470 sqlInsert = None |
| 471 | |
| 472 logging.debug("import excel xml") | |
| 473 | |
| 474 ret="" | |
| 16 | 475 if isinstance(xmldata, str): |
| 14 | 476 logging.debug("importXML reading string data") |
| 16 | 477 doc=parseString(xmldata) |
| 14 | 478 else: |
| 479 logging.debug("importXML reading file data") | |
| 16 | 480 doc=parse(xmldata) |
| 14 | 481 |
| 482 cnt = 0 | |
| 483 while True: | |
| 484 node=doc.getEvent() | |
| 485 | |
| 486 if node is None: | |
| 487 break | |
| 488 | |
| 489 else: | |
| 16 | 490 #logging.debug("tag=%s"%node[1].localName) |
| 14 | 491 if node[1].localName is not None: |
| 492 tagName = node[1].localName.lower() | |
| 493 else: | |
| 494 # ignore non-tag nodes | |
| 495 continue | |
| 16 | 496 |
| 14 | 497 if tagName == rowTagName.lower(): |
| 498 # start of row | |
| 499 doc.expandNode(node[1]) | |
| 500 cnt += 1 | |
| 501 if cnt == 1: | |
| 502 # first row -- field names | |
| 503 names=node[1].getElementsByTagNameNS(namespace, dataTagName) | |
| 504 for name in names: | |
| 505 fn = getTextFromNode(name) | |
| 26 | 506 xmlFields.append({'name':sqlName(fn),'type':'text'}) |
| 14 | 507 |
| 26 | 508 if fieldsOnly: |
| 14 | 509 # return just field names |
| 26 | 510 return xmlFields |
| 14 | 511 |
| 512 # create table | |
| 28 | 513 if fields is None: |
| 31 | 514 fields = xmlFields |
| 515 | |
| 516 sqlFields = self.createEmptyTable(schema, table, fields) | |
| 16 | 517 numFields = len(sqlFields) |
| 15 | 518 fieldString = ", ".join(['"%s"'%f['name'] for f in sqlFields]) |
| 14 | 519 valString = ", ".join(["%s" for f in sqlFields]) |
| 16 | 520 sqlInsert = 'insert into "%s"."%s" (%s) values (%s)'%(schema,table,fieldString,valString) |
| 26 | 521 #logging.debug("importexcelsql: sqlInsert=%s"%sqlInsert) |
| 14 | 522 |
| 523 else: | |
| 524 # following rows are data | |
| 16 | 525 colNodes=node[1].getElementsByTagNameNS(namespace, colTagName) |
| 14 | 526 data = [] |
| 16 | 527 hasData = False |
| 528 for colNode in colNodes: | |
| 529 dataNodes=colNode.getElementsByTagNameNS(namespace, dataTagName) | |
| 530 if len(dataNodes) > 0: | |
| 531 val = getTextFromNode(dataNodes[0]) | |
| 532 hasData = True | |
| 533 else: | |
| 534 val = None | |
| 535 | |
| 14 | 536 data.append(val) |
| 537 | |
| 16 | 538 if not hasData: |
| 539 # ignore empty rows | |
| 540 continue | |
| 541 | |
| 542 # fix number of data fields | |
| 543 if len(data) > numFields: | |
| 544 del data[numFields:] | |
| 545 elif len(data) < numFields: | |
| 546 missFields = numFields - len(data) | |
| 547 data.extend(missFields * [None,]) | |
| 548 | |
| 549 logging.debug("importexcel sqlinsert=%s data=%s"%(sqlInsert,data)) | |
| 17 | 550 self.executeSQL(sqlInsert, data, hasResult=False) |
| 14 | 551 |
| 16 | 552 return cnt |
|
21
a67b7c1f7ec5
Merge with Falks GIS stuff 78e70dfa7ad6b27d10d490f9ae8820306e4fe5d4
casties
diff
changeset
|
553 |
| 19 | 554 # Methods for GoogleMaps creation |
| 555 def showGoogleMap(self,schema='chgis',table='mpdl',id=[],doc=None): | |
| 556 logging.debug("showGoogleMap") | |
| 557 data = self.getDataForGoogleMap(schema,table,id,doc) | |
| 558 kml=self.getKMLname(data=data,table=table) | |
| 559 googleMap_page=self.htmlHead()+str(self.getGoogleMapString(kml=kml)) | |
| 560 return googleMap_page | |
| 561 | |
| 562 def getDataForGoogleMap(self,schema='chgis',table='mpdl',id=[],doc=None): | |
| 563 logging.debug("getDataForGoogleMap") | |
| 564 qstr="SELECT * FROM "+schema+"."+table | |
| 565 try: | |
| 566 if id!=[]: | |
| 567 qstr=qstr+" WHERE " | |
| 568 for id_item in id.split(","): | |
| 569 if table=='mpdl': | |
| 570 qstr=qstr+" mpdl_xmlsource_id = '"+id_item+ "' OR" | |
| 571 else: | |
| 572 qstr=qstr+" cast(id as text) LIKE '"+id_item+ "' OR" | |
| 573 qstr=str(qstr).rsplit(" ",1)[0] #to remove last " and " | |
| 574 data=self.ZSQLSimpleSearch(qstr) | |
| 575 return data | |
| 576 except: | |
| 577 return qstr | |
| 578 | |
| 579 def getKMLname(self,data=[],table=""): | |
| 580 logging.debug("getKMLname") | |
| 581 #session=context.REQUEST.SESSION | |
| 582 kml4Marker="<kml xmlns=\'http://www.opengis.net/kml/2.2\'><Document><Style id=\'marker_icon\'><IconStyle><scale>15</scale><Icon><href>http://chinagis.mpiwg-berlin.mpg.de/chinagis/images/dot_red.png</href></Icon></IconStyle></Style>\n" | |
| 583 initializeStringForGoogleMaps="" | |
| 584 #doLine=container.getVar('doLine') | |
| 585 # Mapping a set of points from table-based SQL-query: | |
| 586 if data!=None: | |
| 587 try: | |
| 588 SQL="""SELECT \"attribute with gis_id\" FROM public.metadata WHERE tablename LIKE '"""+table+"""'""" | |
| 589 gisIDattribute=self.ZSQLSimpleSearch(SQL) | |
| 590 except: | |
| 591 return "table not registered within metadata" | |
| 592 for dataset in data: | |
| 593 try: | |
| 594 xCoord=getattr(dataset,'longitude') | |
| 595 yCoord=getattr(dataset,'latitude') | |
| 596 except: | |
| 597 try: | |
| 598 xCoord=getattr(dataset,'x_coord') | |
| 599 yCoord=getattr(dataset,'y_coord') | |
| 600 except: | |
| 601 # try: | |
| 602 gisID=getattr(dataset,getattr(gisIDattribute[0],'attribute with gis_id')) | |
| 603 coords=self.getPoint4GISid(gisID) | |
| 604 if coords!=None: | |
| 605 xCoord=coords[0] | |
| 606 yCoord=coords[1] | |
| 607 # except: | |
| 608 # return "no coordinates found" | |
| 609 if float(xCoord)!=0: | |
| 610 if float(yCoord)!=0: | |
| 611 kml4Marker=kml4Marker+"<Placemark>" | |
| 612 kml4Marker=kml4Marker+"<description> <![CDATA[<b>" | |
| 613 for values in dataset: | |
| 614 if values != (None, None): | |
| 615 if str(values).find('name')>-1: | |
| 616 kml4Marker=kml4Marker+"<name>"+str(values[1])+"</name>\n" | |
| 617 continue | |
| 618 elif str(values).find('place')>-1: | |
| 619 kml4Marker=kml4Marker+"<name>"+str(values[1])+"</name>\n" | |
| 620 continue | |
| 14 | 621 |
| 19 | 622 kml4Marker=kml4Marker+str(values)+": " |
| 623 attribute_string=str(values).replace("'","__Apostroph__") | |
| 624 attribute_string=str(attribute_string).replace('"','__DoubleApostroph__') | |
| 625 attribute_string=str(attribute_string).replace(';','__$$__') | |
| 626 attribute_string=str(attribute_string).replace('&','&') | |
| 627 if str(attribute_string).find('http')>-1: | |
| 628 attribute_string='<A HREF=' + str(attribute_string) + ' target=_blank>' + str(attribute_string) + '</A>' | |
| 629 kml4Marker=kml4Marker+attribute_string+"</a><br>\n" | |
| 630 | |
| 631 kml4Marker=kml4Marker+"]]></description>\n" | |
| 632 kml4Marker=kml4Marker+"<styleURL>#marker_icon</styleURL>\n" | |
| 633 kml4Marker=kml4Marker+"<Point>" | |
| 634 | |
| 635 kml4Marker=kml4Marker+"<coordinates>"+str(xCoord)+","+str(yCoord)+",0</coordinates>\n" | |
| 636 kml4Marker=kml4Marker+"</Point>\n" | |
| 637 kml4Marker=kml4Marker+"</Placemark>\n" | |
| 14 | 638 |
| 19 | 639 kml4Marker=kml4Marker+"</Document>\n</kml>" |
| 640 kmlFileName="marker"+str(time.time())+".kml" | |
| 14 | 641 |
| 19 | 642 # kml4Marker=str(kml4Marker).replace('&','$$') |
| 643 # kml4Marker=str(kml4Marker).replace(';','__$$__') | |
| 644 # kml4Marker=str(kml4Marker).replace('#','__SHARP__') | |
| 645 initializeStringForGoogleMaps="""onload=\"initialize(\'http://chinagis.mpiwg-berlin.mpg.de/chinagis/REST/daten/"""+kmlFileName+"""\')\""""#+str(data) | |
| 646 initializeStringForGoogleMaps=initializeStringForGoogleMaps.replace("None","0") | |
| 647 isLoadReady='false' | |
| 648 while isLoadReady=='false': | |
| 649 isLoadReady=self.RESTwrite2File(self.daten,kmlFileName,kml4Marker) | |
| 650 | |
| 651 return initializeStringForGoogleMaps | |
| 14 | 652 |
| 19 | 653 def getGoogleMapString(self,kml): |
| 654 logging.debug("getGoogleMapString") | |
| 655 printed= '<body %s> '%kml +"""\n <div id="map_canvas" style="width: 98%; height: 95%"> </div> \n </body>" \n </html>""" | |
| 656 return printed | |
| 657 | |
| 658 def getPoint4GISid(self,gis_id): | |
| 659 j=0 | |
| 660 while (True): | |
| 661 j=j+1 | |
| 662 if (j>100): # FJK: just to prevent endless loops | |
| 663 break | |
| 664 if (gis_id.isdigit()): # FJK: regular exit from while-loop | |
| 665 break | |
| 666 else: | |
| 667 gis_id=gis_id.strip('abcdefghijklmnopqrstuvwxyz_') # FJK: to strip all letters | |
| 668 gis_id=gis_id.strip() # FJK: to strip all whitespaces | |
| 669 resultpoint = [0,0] | |
| 670 results = None | |
| 671 try: | |
| 672 if int(gis_id)>0: | |
| 673 SQL="SELECT x_coord,y_coord FROM chgis.chgis_coords WHERE gis_id LIKE cast("+ str(gis_id) +" as text);" | |
| 674 results=self.ZSQLSimpleSearch(SQL) | |
| 675 #print results | |
| 676 if results != None: | |
| 677 for result in results: | |
| 678 resultpoint=[getattr(result,str('x_coord')),getattr(result,str('y_coord'))] | |
| 679 if resultpoint !=[0,0]: | |
| 680 return resultpoint | |
| 14 | 681 else: |
| 19 | 682 coords=self.getCoordsFromREST_gisID(joinid) |
| 683 SQL="INSERT INTO chgis.chgis_coords (gis_id,x_coord,y_coord) VALUES (" +gis_id+ "," +coords[0][1]+ "," +coords[0][0]+ "); ANALYZE chgis.chgis_coords;" | |
| 684 returnstring=self.ZSQLSimpleSearch(SQL) | |
| 685 return coords[0] | |
| 686 except: | |
| 687 error="gis_id not to interpretable:"+str(gis_id) | |
| 16 | 688 |
| 19 | 689 def getCoordsFromREST_gisID(self,gis_id): |
| 690 coordlist=[] | |
| 691 i=0 | |
| 692 while (i<5 and coordlist==[]): | |
| 13 | 693 |
| 19 | 694 urlresponse=container.urlFunctions.zUrlopenParseString(container.urlFunctions.zUrlopenRead("http://chgis.hmdc.harvard.edu/xml/id/"+gis_id)) |
| 695 baseDocElement=container.urlFunctions.zUrlopenDocumentElement(urlresponse) | |
| 696 childnodes=container.urlFunctions.zUrlopenChildNodes(baseDocElement) | |
| 697 itemnodes=container.urlFunctions.zUrlopenGetElementsByTagName(baseDocElement,'item') | |
| 698 | |
| 699 for i in range(0,container.urlFunctions.zUrlopenLength(itemnodes)): | |
| 700 itemnode=container.urlFunctions.zUrlopenGetItem(itemnodes,i) | |
| 701 itemspatialnodes=container.urlFunctions.zUrlopenGetElementsByTagName(itemnode,'spatial') | |
| 702 for j in range(0,container.urlFunctions.zUrlopenLength(itemspatialnodes)): | |
| 703 coord=[] | |
| 704 itemspatialnode= container.urlFunctions.zUrlopenGetItem(itemspatialnodes,j) | |
| 705 itemspatiallatnodes=container.urlFunctions.zUrlopenGetElementsByTagName(itemspatialnode,'degrees_latitude') | |
| 706 for k in range(0,container.urlFunctions.zUrlopenLength(itemspatiallatnodes)): | |
| 707 itemspatiallatnode= container.urlFunctions.zUrlopenGetItem(itemspatiallatnodes,k) | |
| 708 coord.append(container.urlFunctions.zUrlopenGetTextData(itemspatiallatnode)) | |
| 709 itemspatiallngnodes=container.urlFunctions.zUrlopenGetElementsByTagName(itemspatialnode,'degrees_longitude') | |
| 710 for k in range(0,container.urlFunctions.zUrlopenLength(itemspatiallngnodes)): | |
| 711 itemspatiallngnode= container.urlFunctions.zUrlopenGetItem(itemspatiallngnodes,k) | |
| 712 coord.append(container.urlFunctions.zUrlopenGetTextData(itemspatiallngnode)) | |
| 713 coordlist.append(coord) | |
| 714 gis_id= "_"+gis_id | |
| 715 return coordlist | |
| 716 | |
| 717 # End for GoogleMaps creation | |
| 718 | |
| 719 def RESTwrite2File(self,datadir, name,text): | |
| 720 # try: | |
| 721 fileid=name | |
| 722 if fileid in datadir.objectIds(): | |
| 723 datadir.manage_delObjects(fileid) | |
| 724 newfile=open(name,'w') | |
| 725 newfile.write(text) | |
| 726 newfile.close() | |
| 727 file4Read=open(name,'r') | |
| 728 fileInZope=datadir.manage_addFile(id=fileid,file=file4Read) | |
| 729 return "Write successful" | |
| 730 # except: | |
| 731 # return "Could not write" | |
| 13 | 732 |
|
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
733 |
|
4
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
734 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
|
735 REQUEST=None): |
|
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
736 """Change the object""" |
|
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
737 if title is not None: |
|
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
738 self.title = title |
|
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
739 |
|
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
740 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
|
741 self.connection_id = connection_id |
|
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
742 |
|
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
743 #checkPermission=getSecurityManager().checkPermission |
|
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
744 REQUEST.RESPONSE.redirect('manage_main') |
|
e3ee1f358fe6
new version that doesn't use ZSQLExtend but the database connection more directly.
casties
parents:
2
diff
changeset
|
745 |
|
2
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
746 |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
747 manage_addRestDbInterfaceForm=PageTemplateFile('zpt/addRestDbInterface',globals()) |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
748 |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
749 def manage_addRestDbInterface(self, id, title='', label='', description='', |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
750 createPublic=0, |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
751 createUserF=0, |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
752 REQUEST=None): |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
753 """Add a new object with id *id*.""" |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
754 |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
755 ob=RestDbInterface(str(id),title) |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
756 self._setObject(id, ob) |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
757 |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
758 #checkPermission=getSecurityManager().checkPermission |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
759 REQUEST.RESPONSE.redirect('manage_main') |
|
61a3764cd5fb
new version RestDbInterface with working traversal and templates
casties
parents:
diff
changeset
|
760 |
| 5 | 761 |
