source: exist/trunk/python/ndgeXist/eXistInterface.py @ 3103

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/exist/trunk/python/ndgeXist/eXistInterface.py@3103
Revision 3103, 4.5 KB checked in by lawrence, 12 years ago (diff)

Initial Commit of exist interface for standalone eggification.

Line 
1# Code inspired by example on eXist website.
2import urllib2, base64, urllib, urlparse, httplib, xmlrpclib, types, os
3from xmlHandler2 import xmlHandler as xmlh
4import ndg_xqueries as xq
5
6class InstanceObject(object):
7    def __init__(self, **kw):
8        self.dict={}
9        self.dict.update(kw)
10    def __getattr__(self,arg):
11        return self.dict[arg]
12    def __str__(self):
13        return 'InstanceObject: %s '%self.dict
14       
15class edict(dict):
16    '''An extended dictionary which allows one to set and get values
17    as attributes (kudos Joe Gregorio's 1812)
18    The extended part allows you to get and set values as attributes.
19    That is,
20       d.fred
21    is the same as
22       d['fred']
23    '''
24    def __init__(self,**kw):
25        for a in kw:
26            self[a]=kw[a]
27    def __getattr__(self, key):
28        try:
29            return self.__dict__[key]
30        except KeyError:
31            pass
32        try:
33            assert not key.startswith('_')
34            return self.__getitem__(key)
35        except:
36            raise AttributeError, "object has no attribute '%s'" % key
37    def __setattr__(self, key, value):
38        if key.startswith('_'):
39            self.__dict__[key] = value
40        else:
41            return self.__setitem__(key, value)
42
43
44class  eXist_Connector(object):
45    """Access class for eXist"""
46    def __init__(self,constants=None):
47        ''' Instantiates the eXist connector using supplied constants '''
48        if constants is None: raise 'NoExistConstants'
49        authinfo = urllib2.HTTPPasswordMgrWithDefaultRealm()
50        authinfo.add_password(None,
51                                  constants.host,
52                                  constants.userid,
53                                  constants.password)
54        authHandler = urllib2.HTTPBasicAuthHandler(authinfo)
55        opener = urllib2.build_opener(authHandler)
56        s = constants.userid+':'+constants.password
57        z = base64.encodestring(s)[:-1] # strip trailing 12
58        opener.addheaders.append(('Authorization', 'Basic %s' % z))
59        self.http_headers = {'Authorization':'Basic %s' % z}
60        self.opener = opener
61        # also create an xmlrpc Server object
62       
63        xmlrpc_uri = '%s%s:%s@%s:%d%s' % ( 
64                                            'http://',
65                                            constants.userid,
66                                            constants.password,
67                                            constants.host,
68                                            constants.port,
69                                            constants.xmlrpc_base_path
70                                        )
71        self.xmlrpc = xmlrpclib.Server(xmlrpc_uri)
72
73    def executeQuery(self, xquery, params={}):
74        '''Execute an xquery string, return session and summary information'''
75        xquery=xmlrpclib.Binary(xquery)
76        id = self.xmlrpc.executeQuery(xquery, params)
77        summary = self.xmlrpc.querySummary(id)
78        return id,summary
79
80    def release(self,id):
81        ''' Release an executeQuery session '''
82        self.xmlrpc.releaseQueryResult(id)
83       
84    def retrieve(self,id,pos,params={}):
85        ''' Retrieve a specific document from an executeQuery result set '''
86        return self.xmlrpc.retrieve(id,pos,params).data
87 
88    def executeChunkedQuery(self,xquery,start,number,params={}):
89        ''' Execute a query, return a specific part of the result set, and
90        dump the session automagically '''
91        xquery=xmlrpclib.Binary(xquery)
92        r=self.xmlrpc.query(xquery,number,start,params)
93        return r
94   
95    def querySummary(self,id):
96        ''' Returns a summary of query results for the result-set referenced by id (which was returned by a previous query '''
97        return self.xmlrpc.querySummary(id)
98   
99    def getHits(self,id):
100        ''' Return the number of hits associated with the query that created session id '''
101        return self.xmlrpc.getHits(id)
102   
103    def getDoc(self,collectionName,documentName):
104        ''' Lightweight interface to the getDocument method '''
105        name='%s/%s'%(collectionName,documentName)
106        r=self.xmlrpc.getDocumentAsString(name,{})
107        return r
108   
109# unfortunately it looks like the exist server doesn't support introspection
110#    def showMethods(self):
111#        print self.xmlrpc.system.listMethods()
112       
113
114import unittest
115
116class TestCase(unittest.TestCase):
117       
118    def testedict(self):
119        i=edict(a=1,b=2)
120        i.c=3
121        i['d']=4
122        correct={'a':1,'b':2,'c':3,'d':4}
123        for j in correct: self.assertEqual(correct[j],i[j])
124
125if __name__=="__main__":
126    unittest.main()
127 
Note: See TracBrowser for help on using the repository browser.