changeset 274:9b7db308d2e6

refactor RestDbGisApi to use RestDbInterface from ZDbInterface Product.
author casties
date Thu, 23 Feb 2012 08:35:26 +0100
parents 3a5d51c60e40
children eb8a18f94d2d
files RestDbGisApi.py __init__.py
diffstat 2 files changed, 100 insertions(+), 11 deletions(-) [+]
line wrap: on
line diff
--- a/RestDbGisApi.py	Fri Jan 27 20:02:41 2012 +0100
+++ b/RestDbGisApi.py	Thu Feb 23 08:35:26 2012 +0100
@@ -13,7 +13,7 @@
 import datetime
 import urlFunctions
 
-from RestDbInterface import *
+from Products.ZDBInterface.WritableRestDbInterface import *
 
 
 def kmlEncode(s):
@@ -25,7 +25,7 @@
     return res
 
 
-class RestDbGisApi(RestDbInterface):
+class RestDbGisApi(WritableRestDbInterface):
     """Object for RESTful GIS database queries
     path schema: /db/{schema}/{table}/
     omitting table gives a list of schemas
@@ -34,6 +34,10 @@
     
     meta_type="RESTgis"
 
+    # data templates
+    GIS_schema_table = PageTemplateFile('zpt/GIS_schema_table', globals())
+    KML_schema_table = PageTemplateFile('zpt/KML_schema_table', globals())
+    HTML_schema_usertables = PageTemplateFile('zpt/HTML_schema_usertables', globals())
     
     # and scripts
     def KML_URL_schema_table(self,schema,table, useTimestamp=True, args=None):
@@ -138,12 +142,97 @@
     def createEmptyTable(self,schema,table,fields):
         """create a table with the given fields
            returns list of created fields"""
-        sqlFields = RestDbInterface.createEmptyTable(self,schema,table,fields)
+        sqlFields = WritableRestDbInterface.createEmptyTable(self,schema,table,fields)
         if sqlFields is not None:
             self.setTableMetaTypes(schema,table,sqlFields)
 
         return sqlFields
     
+    # TODO: move this
+    def getAttributeNames(self,schema='public',table=None):   
+        return self.executeSQL("SELECT attname FROM pg_attribute, pg_class WHERE pg_class.oid = attrelid AND attnum>0 AND relname = '%s';"%(table))
+
+    # TODO: move this
+    def getAttributeTypes(self,schema='public',table=None):   
+        return self.executeSQL("SELECT field_name, gis_type FROM public.gis_table_meta_rows WHERE table_name = '%s';"%(table))
+         
+    # TODO: move back to inherited version
+    def showTable(self,format='XML',schema='public',table=None,REQUEST=None,RESPONSE=None):
+        """returns PageTemplate with tables"""
+        logging.debug("showtable")
+        if REQUEST is None:
+            REQUEST = self.REQUEST
+        queryArgs={'doc':None,'id':None}
+        queryArgs['doc'] = REQUEST.get('doc')
+        queryArgs['id'] = REQUEST.get('id')
+    
+        # should be cross-site accessible 
+        if RESPONSE is None:
+            RESPONSE = self.REQUEST.RESPONSE
+            
+        RESPONSE.setHeader('Access-Control-Allow-Origin', '*')
+        
+        # everything else has its own template
+        pt = getattr(self.template, '%s_schema_table'%format, REQUEST)
+        if pt is None:
+            return "ERROR!! template %s_schema_table not found at %s"%(format, self.template )
+        #data = self.getTable(schema,table)
+        return pt(schema=schema,table=table,args=queryArgs)
+
+    #TODO: move to parent class
+    def getLiveUrl(self,schema,table,useTimestamp=True,REQUEST=None):
+        if REQUEST is None:
+            REQUEST = self.REQUEST
+        logging.debug("getLiveUrl")
+        baseUrl = self.absolute_url()
+        timestamp = time.time()
+        # filter parameters in URL and add to new URL
+        params = [p for p in REQUEST.form.items() if p[0] not in ('format','timestamp')]
+        params.append(('format','KML'))
+        if useTimestamp:
+            # add timestamp so URL changes every time
+            params.append(('timestamp',timestamp))
+        paramstr = urllib.urlencode(params)
+        return "%s/db/%s/%s?%s"%(baseUrl,schema,table,paramstr)
+
+
+    # TODO: remove changes from parent version
+    def getTable(self,schema='public',table=None,sortBy=1,username='guest'):
+        """return table data"""
+        logging.debug("gettable")
+        attrNames=self.getAttributeNames(schema,table)
+        attrTypes=self.getAttributeTypes(schema,table)
+        attrString=""
+ #        try:
+        for name in attrNames['rows']:
+              logging.debug("name: ", name[0])
+              not_added=True
+              if name[0] == "the_geom":                        #FJK: the table column is "the_geom"
+                     attrString=attrString+"ST_AsText("+name[0]+"),"
+                     not_added=False
+                     break
+              for a_iter in attrTypes['rows']:
+                 not_added = True
+                 logging.debug("attrTypes.field_name: ", a_iter[0])
+                 if a_iter[0]==name[0]:            
+                     logging.debug("attrTypes.gis_type: ", a_iter[1])            
+                     if a_iter[1] == "the_geom":                        #FJK: the table column is registered in gis_table_meta_rows as type "the_geom"
+                         attrString=attrString+"ST_AsText("+name[0]+"),"
+                         not_added=False
+              if not_added:
+                  if name[0].find('pg.dropped')==-1:
+                      attrString=attrString+name[0]+","
+        attrString=str(attrString).rsplit(",",1)[0] #to remove last ","
+        if sortBy:
+            data = self.executeSQL('select %s from "%s"."%s" order by %s'%(attrString,schema,table,sortBy))
+        else:
+            data = self.executeSQL('select %s from "%s"."%s"'%(attrString,schema,table))
+ #       except:
+            """ table does not exist """
+ #           fields=self.get
+  #          self.createEmptyTable(schema, table, fields)
+        return data
+
     
     def getLiveKmlUrl(self,schema,table,useTimestamp=True,REQUEST=None):
         return self.getLiveUrl(schema,table,useTimestamp,REQUEST)
--- a/__init__.py	Fri Jan 27 20:02:41 2012 +0100
+++ b/__init__.py	Thu Feb 23 08:35:26 2012 +0100
@@ -1,17 +1,17 @@
 
-import RestDbInterface
+#import RestDbInterface
 import RestDbJsonStore
 import RestDbGisApi
 
 def initialize(context):
 
-    context.registerClass(
-         RestDbInterface.RestDbInterface,
-        constructors = (
-          RestDbInterface.manage_addRestDbInterfaceForm,
-          RestDbInterface.manage_addRestDbInterface
-          )
-        )
+#    context.registerClass(
+#         RestDbInterface.RestDbInterface,
+#        constructors = (
+#          RestDbInterface.manage_addRestDbInterfaceForm,
+#          RestDbInterface.manage_addRestDbInterface
+#          )
+#        )
 
     context.registerClass(
          RestDbJsonStore.RestDbJsonStore,