# HG changeset patch
# User fknauft
# Date 1282136425 -7200
# Node ID 78e70dfa7ad6b27d10d490f9ae8820306e4fe5d4
# Parent 060797795a4d228c6f68e8065dcac25baab7099e
GoogleMaps related functions
diff -r 060797795a4d -r 78e70dfa7ad6 RestDbInterface.py
--- a/RestDbInterface.py Wed Aug 18 11:54:18 2010 +0200
+++ b/RestDbInterface.py Wed Aug 18 15:00:25 2010 +0200
@@ -8,9 +8,7 @@
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
from Products.ZSQLExtend import ZSQLExtend
import logging
-import re
-import psycopg2
-import json
+import time
from zope.interface import implements
from zope.publisher.interfaces import IPublishTraverse
@@ -22,34 +20,6 @@
from Products.ZSQLMethods.SQL import SQLConnectionIDs
-def getTextFromNode(node):
- """get the cdata content of a XML node"""
- if node is None:
- return ""
-
- if isinstance(node, list):
- nodelist = node
- else:
- nodelist=node.childNodes
-
- rc = ""
- for node in nodelist:
- if node.nodeType == node.TEXT_NODE:
- rc = rc + node.data
- return rc
-
-def sqlName(s,lc=True):
- """returns restricted ASCII-only version of string"""
- if s is None:
- return ""
-
- # all else -> "_"
- s = re.sub(r'[^A-Za-z0-9_]','_',s)
- if lc:
- return s.lower()
-
- return s
-
class RestDbInterface(Folder):
"""Object for RESTful database queries
path schema: /db/{schema}/{table}/
@@ -84,9 +54,11 @@
self.connection_id = connection_id
# create template folder
self.manage_addFolder('template')
+ # create data folder
+ #self.manage_addFolder('daten')
- def getCursor(self,autocommit=True):
+ def getCursor(self):
"""returns fresh DB cursor"""
conn = getattr(self,"_v_database_connection",None)
if conn is None:
@@ -110,28 +82,19 @@
raise IOError("No database connection! (%s)"%str(e))
cursor = conn.getcursor()
- if autocommit:
- # is there a better version to get to the connection?
- cursor.connection.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
-
return cursor
- def executeSQL(self, query, args=None, hasResult=True, autocommit=True):
+ def executeSQL(self, query, *args):
"""execute query with args on database and return all results.
result format: {"fields":fields, "rows":data}"""
- logging.debug("executeSQL query=%s args=%s"%(query,args))
- cur = self.getCursor(autocommit=autocommit)
+ cur = self.getCursor()
cur.execute(query, args)
# description of returned fields
fields = cur.description
- if hasResult:
- # get all data in an array
- data = cur.fetchall()
- cur.close()
- return {"fields":fields, "rows":data}
- else:
- cur.close()
- return None
+ # get all data in an array
+ data = cur.fetchall()
+ cur.close()
+ return {"fields":fields, "rows":data}
def publishTraverse(self,request,name):
@@ -140,13 +103,9 @@
path = request.get('restdb_path', [])
logging.debug("publishtraverse: name=%s restdb_path=%s"%(name,path))
- if name in ("index_html", "PUT"):
+ if name == "index_html":
# end of traversal
- if request.get("method") == "POST" and request.get("action",None) == "PUT":
- # fake PUT by POST with action=PUT
- name = "PUT"
-
- return getattr(self, name)
+ return self.index_html
#TODO: should we check more?
else:
# traverse
@@ -171,9 +130,15 @@
"""index method"""
# ReST path was stored in request
path = REQUEST.get('restdb_path',[])
+
# type and format are real parameter
format = REQUEST.get('format','HTML').upper()
type = REQUEST.get('type',None)
+
+ # id and doc are used for GoogleMaps content
+ id = REQUEST.get('id',[])
+ doc = REQUEST.get('doc',None)
+
logging.debug("index_html path=%s format=%s type=%s"%(path,format,type))
if type is not None:
@@ -189,40 +154,15 @@
# list of tables
return self.showListOfTables(format=format,schema=path[1])
elif len(path) == 3:
+ # GIS
+ if format=="GIS":
+ return self.showGoogleMap(schema=path[1],table=path[2],id=id,doc=doc)
# table
return self.showTable(format=format,schema=path[1],table=path[2])
# don't know what to do
return str(REQUEST)
- def PUT(self, REQUEST, RESPONSE):
- """
- Implement WebDAV/HTTP PUT/FTP put method for this object.
- """
- logging.debug("RestDbInterface PUT")
- #logging.debug("req=%s"%REQUEST)
- #self.dav__init(REQUEST, RESPONSE)
- #self.dav__simpleifhandler(REQUEST, RESPONSE)
- # ReST path was stored in request
- path = REQUEST.get('restdb_path',[])
- if len(path) == 3:
- schema = path[1]
- tablename = path[2]
- file = REQUEST.get("create_table_file",None)
- if file is None:
- RESPONSE.setStatus(400)
- return
-
- logging.debug("put with schema=%s table=%s file=%s"%(schema,tablename,file))
- ret = self.createTableFromXML(schema, tablename, file)
- # set content type to json(?)
- json.dump(ret, RESPONSE)
-
- else:
- # 400 Bad Request
- RESPONSE.setStatus(400)
- return
-
def showTable(self,format='XML',schema='public',table=None):
"""returns PageTemplate with tables"""
@@ -238,7 +178,7 @@
def getTable(self,schema='public',table=None,username='guest'):
"""return table data"""
logging.debug("gettable")
- data = self.executeSQL('select * from "%s"."%s"'%(schema,table))
+ data = self.executeSQL("select * from %s"%table)
return data
def showListOfTables(self,format='XML',schema='public'):
@@ -279,147 +219,186 @@
# TODO: really look up schemas
data={'fields': (('schemas',),), 'rows': [('public',),]}
return data
-
- def createEmptyTable(self,schema,table,fields):
- """create a table with the given fields
- returns list of created fields"""
- logging.debug("createEmptyTable")
- sqlFields = []
- for f in fields:
- if isinstance(f,dict):
- # {name: XX, type: YY}
- name = sqlName(f['name'])
- type = f['type']
-
- else:
- # name only
- name = sqlName(f)
- type = 'text'
+
+ # Methods for GoogleMaps creation
+ def showGoogleMap(self,schema='chgis',table='mpdl',id=[],doc=None):
+ logging.debug("showGoogleMap")
+ data = self.getDataForGoogleMap(schema,table,id,doc)
+ kml=self.getKMLname(data=data,table=table)
+ googleMap_page=self.htmlHead()+str(self.getGoogleMapString(kml=kml))
+ return googleMap_page
+
+ def getDataForGoogleMap(self,schema='chgis',table='mpdl',id=[],doc=None):
+ logging.debug("getDataForGoogleMap")
+ qstr="SELECT * FROM "+schema+"."+table
+ try:
+ if id!=[]:
+ qstr=qstr+" WHERE "
+ for id_item in id.split(","):
+ if table=='mpdl':
+ qstr=qstr+" mpdl_xmlsource_id = '"+id_item+ "' OR"
+ else:
+ qstr=qstr+" cast(id as text) LIKE '"+id_item+ "' OR"
+ qstr=str(qstr).rsplit(" ",1)[0] #to remove last " and "
+ data=self.ZSQLSimpleSearch(qstr)
+ return data
+ except:
+ return qstr
+
+ def getKMLname(self,data=[],table=""):
+ logging.debug("getKMLname")
+ #session=context.REQUEST.SESSION
+ kml4Marker="
\n"
+
+ kml4Marker=kml4Marker+"]]>