Ejemplo n.º 1
0
 def __call__(self, *args, **kwargs):
     parameters = self._parse_parameters(args, kwargs)
     response, content = Request().post(self.url, data=parameters)
     if response.status == 200:
         results_list = json.loads(content)
         # The returns param is a temporary solution while
         # a proper way to get the data type of returned values by
         # the extensions is implemented in Neo4j
         returns = kwargs.pop("returns", None)
         # Another option is to inspect the results
         if not returns and isinstance(results_list, (tuple, list)):
             returns = results_list[0].get("self", None)
         if results_list and returns:
             if NODE in returns:
                 return [Node(r["self"]) for r in results_list]
             elif RELATIONSHIP in returns:
                 return [Relationship(r["self"]) for r in results_list]
             elif PATH in returns:
                 return [Path(r) for r in results_list]
             elif POSITION in returns:
                 return [Position(r) for r in results_list]
         else:
             return []
     elif response.status == 404:
         raise NotFoundError(response.status, "Extension not found")
     else:
         raise StatusException(response.status, "Invalid data sent")
Ejemplo n.º 2
0
 def __init__(self, url):
     self.url = None
     if url.endswith("/"):
         self.url = url
     else:
         self.url = "%s/" % url
     response, content = Request().get(url)
     if response.status == 200:
         response_json = json.loads(content)
         self._relationship_index = response_json['relationship_index']
         self._node = response_json['node']
         self._node_index = response_json['node_index']
         self._reference_node = response_json['reference_node']
         self._extensions_info = response_json['extensions_info']
         self._extensions = response_json['extensions']
         self.extensions = ExtensionsProxy(self._extensions)
         self.nodes = NodesProxy(self._node, self._reference_node,
                                 self._node_index)
         # Backward compatibility. The current style is more pythonic
         self.node = self.nodes
         # HACK: Neo4j doesn't provide the URLs to access to relationships
         url_parts = self._node.rpartition("node")
         self._relationship = "%s%s%s" % (url_parts[0], RELATIONSHIP,
                                          url_parts[2])
         self.relationships = RelationshipsProxy(self._relationship,
                                                 self._relationship_index)
         self.Traversal = self._get_traversal_class()
     else:
         raise NotFoundError(response.status, "Unable get root")
Ejemplo n.º 3
0
 def _del_properties(self):
     properties_url = self._dic["properties"]
     response, content = Request().delete(properties_url)
     if response.status == 204:
         self._dic["data"] = {}
     else:
         raise NotFoundError(response.status, "Properties not found")
Ejemplo n.º 4
0
 def __getitem__(self, key):
     property_url = self._dic["property"].replace("{key}", key)
     response, content = Request().get(property_url)
     if response.status == 200:
         self._dic["data"][key] = json.loads(content)
     else:
         raise NotFoundError(response.status, "Node or propery not found")
     return self._dic["data"][key]
Ejemplo n.º 5
0
 def __delitem__(self, key):
     property_url = self._dic["property"].replace("{key}", key)
     response, content = Request().delete(property_url)
     if response.status == 204:
         del self._dic["data"][key]
     elif response.status == 404:
         raise NotFoundError(response.status, "Node or property not found")
     else:
         raise StatusException(response.status, "Node or propery not found")
Ejemplo n.º 6
0
 def __setitem__(self, key, value):
     property_url = self._dic["property"].replace("{key}", key)
     response, content = Request().put(property_url, data=value)
     if response.status == 204:
         self._dic["data"].update({key: value})
     elif response.status == 404:
         raise NotFoundError(response.status, "Node or property not found")
     else:
         raise StatusException(response.status, "Invalid data sent")
Ejemplo n.º 7
0
 def get(self, attr, *args, **kwargs):
     if attr in self._dict.keys():
         return self.__getattr__(attr)
     else:
         if args:
             return args[0]
         elif "default" in kwargs:
             return kwargs["default"]
         else:
             raise NotFoundError()
Ejemplo n.º 8
0
 def get(self, key, *args, **kwargs):
     try:
         return self.__getitem__(key)
     except (KeyError, NotFoundError, StatusException):
         if args:
             return args[0]
         elif "default" in kwargs:
             return kwargs["default"]
         else:
             raise NotFoundError()
Ejemplo n.º 9
0
 def _set_properties(self, props={}):
     if not props:
         return None
     properties_url = self._dic["properties"]
     response, content = Request().put(properties_url, data=props)
     if response.status == 204:
         self._dic["data"] = props.copy()
         return props
     elif response.status == 400:
         raise StatusException(response.status, "Invalid data sent")
     else:
         raise NotFoundError(response.status, "Properties not found")
Ejemplo n.º 10
0
 def delete(self, key=None):
     if key:
         self.__delitem__(key)
         return
     response, content = Request().delete(self.url)
     if response.status == 204:
         del self
     elif response.status == 404:
         raise NotFoundError(response.status, "Node or property not found")
     else:
         raise StatusException(response.status, "Node could not be "\
                                                "deleted (still has " \
                                                "relationships?)")
Ejemplo n.º 11
0
 def __init__(self, url, create=False, data={}):
     self._dic = {}
     self.url = None
     if url.endswith("/"):
         url = url[:-1]
     if create:
         response, content = Request().post(url, data=data)
         if response.status == 201:
             self._dic.update(data.copy())
             self.url = response.get("location")
         else:
             raise NotFoundError(response.status, "Invalid data sent")
     if not self.url:
         self.url = url
     response, content = Request().get(self.url)
     if response.status == 200:
         self._dic.update(json.loads(content).copy())
         self._extensions = self._dic.get('extensions', {})
         if self._extensions:
             self.extensions = ExtensionsProxy(self._extensions)
     else:
         raise NotFoundError(response.status, "Unable get object")
Ejemplo n.º 12
0
 def __init__(self, url):
     self._dic = {}
     if url.endswith("/"):
         url = url[:-1]
     self.url = url
     response, content = Request().get(self.url)
     if response.status == 200:
         self._dic.update(json.loads(content).copy())
         self.description = self._dic['description']
         self.name = self._dic['name']
         self.extends = self._dic['extends']
         self.parameters = self._dic['parameters']
     else:
         raise NotFoundError(response.status, "Unable get extension")
Ejemplo n.º 13
0
 def request(self, return_type):
     try:
         return self._cache[return_type]
     except KeyError:
         url = self._endpoint.replace("{returnType}", return_type)
         response, content = Request(**self._auth).post(url,
                                                        data=self._data)
         if response.status == 200:
             results_list = json.loads(content)
             self._cache[return_type] = results_list
             return results_list
         elif response.status == 404:
             raise NotFoundError(response.status, "Node or relationship " \
                                                  "not found")
         raise StatusException(response.status, "Invalid data sent")
Ejemplo n.º 14
0
 def traverse(self, types=None, order=None, stop=None, returnable=None,
              uniqueness=None, is_stop_node=None, is_returnable=None,
              returns=None):
     data = {}
     if order in (BREADTH_FIRST, DEPTH_FIRST):
         data.update({"order": order})
     if isinstance(stop, (int, float)) or stop is STOP_AT_END_OF_GRAPH:
         data.update({"max depth": stop})
     if returnable in (BREADTH_FIRST, DEPTH_FIRST):
         data.update({"return filter": {
                         "language": "builtin",
                         "name": returnable,
         }})
     if uniqueness in (NODE_GLOBAL, NODE_PATH, NODE_RECENT, NODE,
                       RELATIONSHIP_GLOBAL, RELATIONSHIP_PATH,
                       RELATIONSHIP_RECENT):
         data.update({"uniqueness": uniqueness})
     if types:
         if not isinstance(types, (list, tuple)):
             types = [types]
         relationships = []
         for relationship in types:
             if relationship.direction == "both":
                 relationships.append({"type": relationship.type})
             else:
                 relationships.append({"type": relationship.type,
                                       "direction": relationship.direction})
         if relationships:
             data.update({"relationships": relationships})
     if returns not in (NODE, RELATIONSHIP, PATH, POSITION):
         returns = NODE
     traverse_url = self._dic["traverse"].replace("{returnType}", returns)
     response, content = Request().post(traverse_url, data=data)
     if response.status == 200:
         results_list = json.loads(content)
         if returns is NODE:
             return [Node(r["self"]) for r in results_list]
         elif returns is RELATIONSHIP:
             return [Relationship(r["self"]) for r in results_list]
         elif returns is PATH:
             return [Path(r) for r in results_list]
         elif returns is POSITION:
             return [Position(r) for r in results_list]
     elif response.status == 404:
         raise NotFoundError(response.status, "Node or relationship not " \
                                              "found")
     else:
         raise StatusException(response.status, "Invalid data sent")
Ejemplo n.º 15
0
 def _get_results(self, url):
     response, content = Request().get(url)
     if response.status == 200:
         data_list = json.loads(content)
         if self._index_for == NODE:
             return [Node(n['self'], data=n['data'])
                     for n in data_list]
         else:
             return [Relationship(r['self'], data=r['data'])
                     for r in data_list]
     elif response.status == 404:
         raise NotFoundError(response.status,
                             "Node or relationship not found")
     else:
         raise StatusException(response.status,
                               "Error requesting index with GET %s" \
                                % url)
Ejemplo n.º 16
0
 def relationship(to, *args, **kwargs):
     create_relationship_url = self._dic["create_relationship"]
     data = {
         "to": to.url,
         "type": relationship_name,
     }
     if kwargs:
         data.update({"data": kwargs})
     response, content = Request().post(create_relationship_url,
                                        data=data)
     if response.status == 201:
         return Relationship(response.get("location"))
     elif response.status == 404:
         raise NotFoundError(response.status, "Node specified by the " \
                                              "URI not of \"to\" node" \
                                              "not found")
     else:
         raise StatusException(response.status, "Invalid data sent")
Ejemplo n.º 17
0
 def _get_dict(self):
     indexes_dict = {}
     response, content = Request().get(self.url)
     if response.status == 200:
         indexes_dict = json.loads(content)
         for index_name, index_properties in indexes_dict.items():
             index_props = {}
             for key, val in index_properties.items():
                 index_props[str(key)] = val
             indexes_dict[index_name] = Index(self._index_for, index_name,
                                              **index_props)
         return indexes_dict
     elif response.status == 404:
         raise NotFoundError(response.status, "Indexes not found")
     elif response.status == 204:
         return indexes_dict
     else:
         raise StatusException(response.status,
                               "Error requesting indexes with GET %s" \
                                % self.url)
Ejemplo n.º 18
0
 def get_relationships(types=None, *args, **kwargs):
     if relationship_type in ["all", "incoming", "outgoing"]:
         if types and isinstance(types, (tuple, list)):
             key = "%s_typed_relationships" % relationship_type
             url_string = self._node._dic[key]
             url = url_string.replace(self._pattern, "&".join(types))
         else:
             key = "%s_relationships" % relationship_type
             url = self._node._dic[key]
         response, content = Request().get(url)
         if response.status == 200:
             relationship_list = json.loads(content)
             relationships = [Relationship(r["self"])
                              for r in relationship_list]
             return relationships
         elif response.status == 404:
             raise NotFoundError(response.status,
                                 "Node or relationship not found")
         else:
             raise StatusException(response.status, "Node not found")
     raise NameError("name %s is not defined" % relationship_type)
Ejemplo n.º 19
0
 def delete(self, key, value, item):
     if not isinstance(item, Base):
         raise TypeError("%s has no url attribute" % item)
     if key and value:
         key = urllib.quote(key)
         value = urllib.quote(value)
         url = self.template.replace("{key}", key).replace("{value}", value)
         url = "%s/%s" % (url, item.id)
     elif key and not value:
         key = urllib.quote(key)
         url = "%s/%s" % (self.template.replace("{key}", key), item.id)
     elif not key and not value:
         url = self.template.replace("{key}/{value}", item.id)
     else:
         raise TypeError("remove() take at least 2 arguments, the key " \
                         "of the index and the %s to remove"
                         % self._index_for)
     response, content = Request().delete(url)
     if response.status == 404:
         raise NotFoundError(response.status,
                             "%s not found" % self._index_for.capitalize())
     elif response.status != 204:
         raise StatusException(response.status)