source: exist/trunk/python/ndgUtils/eXistConnector.py @ 4010

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/exist/trunk/python/ndgUtils/eXistConnector.py@4010
Revision 4010, 4.5 KB checked in by cbyrom, 11 years ago (diff)

Implement usage of overwrite keyword in eXistConnector.storeXML method.

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