def wrapper(*args, **kwargs): try: return f(*args, **kwargs) except (socket.timeout, requests.exceptions.ReadTimeout) as e: raise ExistDBTimeout(e) except (socket.error, xmlrpclib.Fault, \ xmlrpclib.ProtocolError, xmlrpclib.ResponseError) as e: raise ExistDBException(e)
def removeCollection(self, collection_name): """Remove the named collection from the database. :param collection_name: string name of collection :rtype: boolean indicating success """ if (not self.hasCollection(collection_name)): raise ExistDBException(collection_name + " does not exist") logger.debug('removeCollection %s' % collection_name) return self.server.removeCollection(collection_name)
def createCollection(self, collection_name, overwrite=False): """Create a new collection in the database. :param collection_name: string name of collection :param overwrite: overwrite existing document? :rtype: boolean indicating success """ if not overwrite and self.hasCollection(collection_name): raise ExistDBException(collection_name + " exists") logger.debug('createCollection %s' % collection_name) return self.server.createCollection(collection_name)
def getDocument(self, name): """Retrieve a document from the database. :param name: database document path to retrieve :rtype: string contents of the document """ # REST api; need an error wrapper? logger.debug('getDocument %s' % self.restapi_path(name)) response = self.session.get(self.restapi_path(name), stream=False) if response.status_code == requests.codes.ok: return response.content if response.status_code == requests.codes.not_found: # matching previous xmlrpc behavior; # TODO: use custom exception classes here raise ExistDBException('%s not found' % name)
def test_message(self): # generic exception msg_text = 'this is a basic exception message' err = ExistDBException(Exception(msg_text)) self.assertEqual(msg_text, err.message()) # socket timeout err = ExistDBException(socket.timeout()) self.assertEqual('Request Timed Out', err.message()) # xmlrpc error # - args are url, error code, error message, headers rpc_err = xmlrpclib.ProtocolError('http://so.me/url', 101, 'rpc error message', {}) err = ExistDBException(rpc_err) # message should contain various bits of info from exception msg = err.message() self.assert_('XMLRPC Error' in msg) self.assert_(rpc_err.url in msg) self.assert_(str(rpc_err.errcode) in msg) self.assert_(rpc_err.errmsg in msg)
def reindexCollection(self, collection_name): """Reindex a collection. Reindex will fail if the eXist user does not have the correct permissions within eXist (must be a member of the DBA group). :param collection_name: string name of collection :rtype: boolean success """ if (not self.hasCollection(collection_name)): raise ExistDBException(collection_name + " does not exist") # xquery reindex function requires that collection name begin with /db/ if collection_name[0:3] != '/db': collection_name = '/db/' + collection_name.strip('/') result = self.query("xmldb:reindex('%s')" % collection_name) return result.values[0] == 'true'
def hasCollection(self, collection_name): """Check if a collection exists. :param collection_name: string name of collection :rtype: boolean """ try: logger.debug('describeCollection %s' % collection_name) self.server.describeCollection(collection_name) return True except Exception as e: # now could be generic ProtocolError s = "collection " + collection_name + " not found" if hasattr(e, 'faultCode') and (e.faultCode == 0 and s in e.faultString): return False else: raise ExistDBException(e)
def query(self, xquery=None, start=1, how_many=10, cache=False, session=None, release=None, result_type=None): """Execute an XQuery query, returning the results directly. :param xquery: a string XQuery query :param start: first index to return (1-based) :param how_many: maximum number of items to return :param cache: boolean, to cache a query and return a session id (optional) :param session: session id, to retrieve a cached session (optional) :param release: session id to be released (optional) :rtype: the resultType specified at the creation of this ExistDB; defaults to :class:`QueryResult`. """ # xml_s = self.server.query(xquery, how_many, start, kwargs) params = { '_howmany': how_many, '_start': start, } if xquery is not None: params['_query'] = xquery if cache: params['_cache'] = 'yes' if release is not None: params['_release'] = release if session is not None: params['_session'] = session if result_type is None: result_type = self.resultType opts = ' '.join('%s=%s' % (key.lstrip('_'), val) for key, val in params.iteritems() if key != '_query') if xquery: debug_query = '\n%s' % xquery else: debug_query = '' logger.debug('query %s%s' % (opts, debug_query)) response = self.session.get(self.restapi_path(''), params=params, stream=False) if response.status_code == requests.codes.ok: # successful release doesn't return any content if release is not None: return True # successfully released # TODO: test unicode handling return xmlmap.load_xmlobject_from_string(response.content, result_type) # 400 bad request returns an xml error we can parse elif response.status_code == requests.codes.bad_request: err = xmlmap.load_xmlobject_from_string(response.content, ExistExceptionResponse) raise ExistDBException(err.message) # not sure if any information is available on other error codes else: raise ExistDBException(response.content)