comparison RestDbInterface.py @ 2:61a3764cd5fb

new version RestDbInterface with working traversal and templates
author casties
date Fri, 21 May 2010 11:48:30 +0000
parents
children e3ee1f358fe6
comparison
equal deleted inserted replaced
1:48de7c260ffe 2:61a3764cd5fb
1 '''
2 Created on 19.5.2010
3
4 @author: casties
5 '''
6
7 from OFS.Folder import Folder
8 from Products.PageTemplates.PageTemplateFile import PageTemplateFile
9 from Products.ZSQLExtend import ZSQLExtend
10 import logging
11
12 from zope.interface import implements
13 from zope.publisher.interfaces import IPublishTraverse
14 from ZPublisher.BaseRequest import DefaultPublishTraverse
15 #from zope.publisher.interfaces import NotFound
16 #from zope.app import zapi
17 #from zope.component import queryMultiAdapter
18
19
20 class RestDbInterface(Folder):
21 """Object for RESTful database queries
22 path schema: /[XML,JSON,HTML]/{schema}/{table}/
23 omitting table gives a list of schemas
24 omitting table and schema gives a list of schemas
25 """
26 implements(IPublishTraverse)
27
28 meta_type="RESTdb"
29
30 # data templates
31 XML_list_schemas = PageTemplateFile('zpt/XML_list_schemas', globals())
32 XML_list_tables = PageTemplateFile('zpt/XML_list_tables', globals())
33 XML_table = PageTemplateFile('zpt/XML_table', globals())
34 HTML_list_schemas = PageTemplateFile('zpt/HTML_list_schemas', globals())
35 HTML_list_tables = PageTemplateFile('zpt/HTML_list_tables', globals())
36 HTML_table = PageTemplateFile('zpt/HTML_table', globals())
37
38
39
40 def __init__(self, id, title):
41 """init"""
42 self.id = id
43 self.title = title
44 # create template folder
45 self.manage_addFolder('template')
46
47
48 def publishTraverse(self,request,name):
49 """change the traversal"""
50 # get stored path
51 path = request.get('restdb_path', [])
52 logging.debug("publishtraverse: name=%s restdb_path=%s"%(name,path))
53
54 if name == "index_html":
55 # end of traversal
56 return self.index_html
57 #TODO: should we check more?
58 else:
59 # traverse
60 if len(path) == 0:
61 # first segment
62 if name in ['XML','JSON','HTML']:
63 # virtual path -- continue traversing
64 path = [name]
65 request['restdb_path'] = path
66 else:
67 # try real path
68 tr = DefaultPublishTraverse(self, request)
69 ob = tr.publishTraverse(request, name)
70 return ob
71 else:
72 path.append(name)
73
74 # continue traversing
75 return self
76
77 def index_html(self,REQUEST,RESPONSE):
78 """index method"""
79 path = REQUEST.get('restdb_path',[])
80 logging.debug("index_html path=%s"%path)
81 if len(path) == 1:
82 # list of schemas
83 return self.showListOfSchemas(format=path[0])
84 elif len(path) == 2:
85 # list of tables
86 return self.showListOfTables(format=path[0],schema=path[1])
87 elif len(path) == 3:
88 # table
89 return self.showTable(format=path[0],schema=path[1],table=path[2])
90
91 # don't know what to do
92 return str(REQUEST)
93
94
95 def showTable(self,format='XML',schema='public',table=None):
96 """returns PageTemplate with tables"""
97 logging.debug("showtable")
98 pt = getattr(self.template, '%s_table'%format, None)
99 if pt is None:
100 return "ERROR!! template %s_table not found"%format
101
102 data = self.getTable(schema,table)
103 return pt(data=data,tablename=table)
104
105
106 def getTable(self,schema='public',table=None,username='guest'):
107 """return table data"""
108 logging.debug("gettable")
109 qstr="select * from %s"%table
110 data=self.ZSQLSimpleSearch(qstr)
111 return data
112
113 def showListOfTables(self,format='XML',schema='public'):
114 """returns PageTemplate with list of tables"""
115 logging.debug("showlistoftables")
116 pt = getattr(self.template, '%s_list_tables'%format, None)
117 if pt is None:
118 return "ERROR!! template %s_list_tables not found"%format
119
120 data = self.getListOfTables(schema)
121 return pt(data=data,schema=schema)
122
123 def getListOfTables(self,schema='public',username='guest'):
124 """return list of tables"""
125 logging.debug("getlistoftables")
126 # get list of fields and types of db table
127 qstr="""select c.relname FROM pg_catalog.pg_class c
128 LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
129 WHERE c.relkind IN ('r','') AND n.nspname NOT IN ('pg_catalog', 'pg_toast')
130 AND pg_catalog.pg_table_is_visible(c.oid)"""
131 #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"
132 data=self.ZSQLSimpleSearch(qstr)
133 return data
134
135 def showListOfSchemas(self,format='XML'):
136 """returns PageTemplate with list of schemas"""
137 logging.debug("showlistofschemas")
138 pt = getattr(self.template, '%s_list_schemas'%format, None)
139 if pt is None:
140 return "ERROR!! template %s_list_schemas not found"%format
141
142 data = self.getListOfSchemas()
143 return pt(data=data)
144
145 def getListOfSchemas(self,username='guest'):
146 """return list of schemas"""
147 logging.debug("getlistofschemas")
148 # TODO: really look up schemas
149 data=['public']
150 return data
151
152
153
154 manage_addRestDbInterfaceForm=PageTemplateFile('zpt/addRestDbInterface',globals())
155
156 def manage_addRestDbInterface(self, id, title='', label='', description='',
157 createPublic=0,
158 createUserF=0,
159 REQUEST=None):
160 """Add a new object with id *id*."""
161
162 ob=RestDbInterface(str(id),title)
163 self._setObject(id, ob)
164
165 #checkPermission=getSecurityManager().checkPermission
166 REQUEST.RESPONSE.redirect('manage_main')
167
168