Exemplo n.º 1
0
 def _create(self, postData):
     """Creates an index of any type according to postData"""
     if self.infos is None:
         r = self.connection.session.post(
             self.indexesURL,
             params={"collection": self.collection.name},
             data=json.dumps(postData))
         data = r.json()
         if (r.status_code >= 400) or data['error']:
             raise CreationError(data['errorMessage'], data)
         self.infos = data
Exemplo n.º 2
0
 def createDatabase(self, name, **dbArgs):
     "use dbArgs for arguments other than name. for a full list of arguments please have a look at arangoDB's doc"
     dbArgs['name'] = name
     payload = json.dumps(dbArgs)
     r = requests.post(self.databasesURL, data=payload)
     data = r.json()
     if r.status_code == 201 and not data["error"]:
         db = Database(self, name)
         self.databases[name] = db
         return self.databases[name]
     else:
         raise CreationError(data["errorMessage"], data)
Exemplo n.º 3
0
	def createVertex(self, collectionName, docAttributes, waitForSync = False) :
		"""adds a vertex to the graph and returns it"""
		url = "%s/vertex/%s" % (self.URL, collectionName)
		self.database[collectionName].validateDct(docAttributes)

		r = requests.post(url, data = json.dumps(docAttributes), params = {'waitForSync' : waitForSync})
		
		data = r.json()
		if r.status_code == 201 or r.status_code == 202 :
			return self.database[collectionName][data["vertex"]["_key"]]
		
		raise CreationError("Unable to create vertice, %s" % data["errorMessage"], data)
Exemplo n.º 4
0
	def _developDoc(self, i) :
		"""private function that transforms a json returned by ArangoDB into a pyArango Document or Edge"""
		docJson = self.result[i]
		try :
			collection = self.database[docJson["_id"].split("/")[0]]
		except KeyError :
			raise CreationError("result %d is not a valid Document. Try setting rawResults to True" % i)

		if collection.type == COL.COLLECTION_EDGE_TYPE :
			self.result[i] = Edge(collection, docJson)
 		else :
 			self.result[i] = Document(collection, docJson)
Exemplo n.º 5
0
    def createCollection(self,
                         className='GenericCollection',
                         waitForSync=False,
                         **colArgs):
        """Creeats a collection and returns it.
		ClassName the name of a class inheriting from Collection or Egdes. Use colArgs to put things such as 'isVolatile = True' (see ArangoDB's doc
		for a full list of possible arugments)."""

        if className != 'GenericCollection':
            colArgs['name'] = className
        else:
            if 'name' not in colArgs:
                raise ValueError(
                    "a 'name' argument mush be supplied if you want to create a generic collection"
                )

        colClass = COL.getCollectionClass(className)

        if colArgs['name'] in self.collections:
            raise CreationError(
                "Database %s already has a collection named %s" %
                (self.name, colArgs['name']))

        if issubclass(colClass, COL.Edges):
            colArgs["type"] = COL.COLLECTION_EDGE_TYPE
        else:
            colArgs["type"] = COL.COLLECTION_DOCUMENT_TYPE

        colArgs["waitForSync"] = waitForSync

        payload = json.dumps(colArgs)
        r = requests.post(self.collectionsURL, data=payload)
        data = r.json()
        if r.status_code == 200 and not data["error"]:
            col = colClass(self, data)
            self.collections[col.name] = col
            return self.collections[col.name]
        else:
            raise CreationError(data["errorMessage"], data)
Exemplo n.º 6
0
	def createEdge(self, collectionName, _fromId, _toId, edgeAttributes, waitForSync = False) :
		"""creates an edge between two documents"""
		
		if collectionName not in self.definitions :
			raise KeyError("'%s' is not among the edge definitions" % collectionName)
		
		url = "%s/edge/%s" % (self.URL, collectionName)
		self.database[collectionName].validateDct(edgeAttributes)
		payload = edgeAttributes
		payload.update({'_from' : _fromId, '_to' : _toId})

		r = requests.post(url, data = json.dumps(payload), params = {'waitForSync' : waitForSync})
		data = r.json()
		if r.status_code == 201 or r.status_code == 202 :
			return self.database[collectionName][data["edge"]["_key"]]
		raise CreationError("Unable to create edge, %s" % r.json()["errorMessage"], data)
Exemplo n.º 7
0
    def save(self, waitForSync=False, **docArgs):
        """Saves the document to the database by either performing a POST (for a new document) or a PUT (complete document overwrite).
		If you want to only update the modified fields use the .path() function.
		Use docArgs to put things such as 'waitForSync = True' (for a full list cf ArangoDB's doc).
		It will only trigger a saving of the document if it has been modified since the last save. If you want to force the saving you can use forceSave()"""

        if self.modified:
            if self.collection._validation['on_save']:
                self.validate(patch=False)

            params = dict(docArgs)
            params.update({
                'collection': self.collection.name,
                "waitForSync": waitForSync
            })
            payload = {}
            payload.update(self._store)

            if self.URL is None:
                if self._key is not None:
                    payload["_key"] = self._key
                payload = json.dumps(payload)
                r = self.connection.session.post(self.documentsURL,
                                                 params=params,
                                                 data=payload)
                update = False
            else:
                payload = json.dumps(payload)
                r = self.connection.session.put(self.URL,
                                                params=params,
                                                data=payload)
                update = True

            data = r.json()
            if (r.status_code == 201
                    or r.status_code == 202) and not data['error']:
                if update:
                    self._rev = data['_rev']
                else:
                    self.setPrivates(data)
            else:
                if update:
                    raise UpdateError(data['errorMessage'], data)
                else:
                    raise CreationError(data['errorMessage'], data)

            self.modified = False
Exemplo n.º 8
0
    def createGraph(self, name, createCollections=True):
        """Creates a graph and returns it. 'name' must be the name of a class inheriting from Graph.
		You can decide weither or not you want non existing collections to be created by setting the value of 'createCollections'.
		If the value if 'false' checks will be performed to make sure that every collection mentionned in the edges definition exist. Raises a ValueError in case of
		a non-existing collection."""
        def _checkCollectionList(lst):
            for colName in lst:
                if not COL.isCollection(colName):
                    raise ValueError("'%s' is not a defined Collection" %
                                     colName)

        graphClass = GR.getGraphClass(name)

        ed = []
        for e in graphClass._edgeDefinitions:
            if not createCollections:
                if not COL.isEdgeCollection(e.edgesCollection):
                    raise ValueError("'%s' is not a defined Edge Collection" %
                                     e.edgesCollection)
                _checkCollectionList(e.fromCollections)
                _checkCollectionList(e.toCollections)

            ed.append(e.toJson())

        if not createCollections:
            _checkCollectionList(graphClass._orphanedCollections)

        payload = {
            "name": name,
            "edgeDefinitions": ed,
            "orphanCollections": graphClass._orphanedCollections
        }

        payload = json.dumps(payload)
        r = requests.post(self.graphsURL, data=payload)
        data = r.json()
        if r.status_code == 201:
            self.graphs[name] = graphClass(self, data["graph"])
        else:
            raise CreationError(data["errorMessage"], data)
        return self.graphs[name]