Пример #1
0
 def get(self, **kwargs):
     data = u""
     if kwargs:
         data = []
         for k, v in kwargs.items():
             data.append("{}={}".format(smart_quote(k),
                                        smart_quote(json.dumps(v))))
         data = u"?{}".format(u"&".join(data))
     url = self._url.replace(
         u"labels",
         u"label/{}/nodes{}".format(smart_quote(self._label), data))
     response = Request(**self._auth).get(url)
     if response.status_code == 200:
         results_list = response.json()
         if not results_list:
             return []
         elif isinstance(results_list, (tuple, list)):
             return Iterable(self._node_cls, results_list, "self",
                             auth=self._auth)
     else:
         msg = "Unable to read label(s)"
         try:
             msg += ": " + response.json().get('message')
         except (ValueError, AttributeError, KeyError):
             pass
         raise StatusException(response.status_code, msg)
Пример #2
0
 def _discard(self, label=None, return_label=False, raise_error=False):
     if not label:
         label = self._labels.pop()
     try:
         url = "{}/{}".format(self._url, smart_quote(label))
     except AttributeError:
         url = "{}/{}".format(self._url, smart_quote(label._label))
     response = Request(**self._auth).delete(url)
     if response.status_code == 204:
         _label = label
         if not isinstance(_label, Label):
             _label = Label(self._url, label)
         if _label in self._labels:
             self._labels.remove(_label)
         if return_label:
             return _label
     elif raise_error:
         if options.SMART_ERRORS:
             raise KeyError("'{}' not found".format(_label))
         else:
             msg = "Unable to remove label"
             try:
                 msg += ": " + response.json().get('message')
             except (ValueError, AttributeError, KeyError):
                 pass
             raise StatusException(response.status_code, msg)
Пример #3
0
 def add(self, labels):
     single = False
     if not isinstance(labels, (tuple, list)):
         labels = [labels]
         single = True
     response = Request(**self._auth).post(self._url, data=labels)
     added = set()
     if response.status_code == 204:
         for label in labels:
             _label = label
             if not isinstance(_label, Label):
                 _label = Label(self._url, label, auth=self._auth,
                                cypher=self._cypher, node=self._node_cls)
             if _label not in self._labels:
                 self._labels.add(_label)
                 added.add(_label)
     else:
         msg = "Unable to add label"
         try:
             msg += ": " + response.json().get('message')
         except (ValueError, AttributeError, KeyError):
             pass
         raise StatusException(response.status_code, msg)
     if single:
         return added.pop()
     else:
         return added
Пример #4
0
 def _discard(self, label=None, return_label=False, raise_error=False):
     if not label:
         label = self._labels.pop()
     try:
         url = "{}/{}".format(self._url, smart_quote(label))
     except AttributeError:
         url = "{}/{}".format(self._url, smart_quote(label._label))
     response = Request(**self._auth).delete(url)
     if response.status_code == 204:
         _label = label
         if not isinstance(_label, Label):
             _label = Label(self._url, label)
         if _label in self._labels:
             self._labels.remove(_label)
         if return_label:
             return _label
     elif raise_error:
         if options.SMART_ERRORS:
             raise KeyError("'{}' not found".format(_label))
         else:
             msg = "Unable to remove label"
             try:
                 msg += ": " + response.json().get('message')
             except (ValueError, AttributeError, KeyError):
                 pass
             raise StatusException(response.status_code, msg)
Пример #5
0
 def _request(self, url, statements=None):
     if statements is None:
         statements = []
     request = Request(**self._class._auth)
     data = {"statements": statements}
     response = request.post(url, data=data)
     if response.status_code in [200, 201]:
         return response
     else:
         raise TransactionException(response.status_code)
Пример #6
0
 def _request(self, url, statements=None):
     if statements is None:
         statements = []
     request = Request(**self._class._auth)
     data = {
         "statements": statements
     }
     response = request.post(url, data=data)
     if response.status_code in [200, 201]:
         return response
     else:
         raise TransactionException(response.status_code)
Пример #7
0
 def get_response(self):
     # Preparing slicing and ordering
     q = self.q
     params = self.params
     version = self._auth.get('version', None)
     NEO4J_V2 = version and version.split(".")[0] >= "2"
     if self._order_by:
         orders = []
         for o, order in enumerate(self._order_by):
             order_key = "_order_by_%s" % o
             if order_key not in params:
                 if NEO4J_V2:
                     orders.append(u"n.`{%s}` %s"
                                   % (order_key, order[1]))
                 else:
                     nullable = ""
                     if len(order) == 3:
                         if order[2] is True:
                             nullable = "!"
                         elif order[2] is False:
                             nullable = "?"
                     orders.append(u"n.`{%s}`%s %s" % (order_key, nullable,
                                                       order[1]))
                 params[order_key] = order[0]
         if orders:
             q = u"%s order by %s" % (q, ", ".join(orders))
     # Lazy slicing
     if isinstance(self._skip, int) and "_skip" not in params:
         q = u"%s skip {_skip} " % q
         params["_skip"] = self._skip
     if isinstance(self._limit, int) and "_limit" not in params:
         q = u"%s limit {_limit} " % q
         params["_limit"] = self._limit
     # Making the real resquest
     data = {
         "query": q,
         "params": params,
     }
     response = Request(**self._auth).post(self._cypher, data=data)
     if response.status_code == 200:
         response_json = response.json()
         return response_json
     elif response.status_code == 400:
         err_msg = u"Cypher query exception"
         try:
             err_msg = "%s: %s" % (err_msg, response.json()["message"])
         except:
             err_msg = "%s: %s" % (err_msg, response.text)
         raise CypherException(err_msg)
     else:
         raise StatusException(response.status_code, "Invalid data sent")
Пример #8
0
 def request(self, return_type):
     try:
         return self._cache[return_type]
     except KeyError:
         url = self._endpoint.replace("{returnType}", return_type)
         response = Request(**self._auth).post(url, data=self._data)
         if response.status_code == 200:
             results_list = response.json()
             self._cache[return_type] = results_list
             return results_list
         elif response.status_code == 404:
             raise NotFoundError(response.status_code,
                                 "Node or relationship not found")
         raise StatusException(response.status_code, "Invalid data sent")
Пример #9
0
 def _update_labels(self):
     response = Request(**self._auth).get(self._url)
     if response.status_code == 200:
         results_list = response.json()
         return set([Label(self._url, label, auth=self._auth,
                           cypher=self._cypher, node=self._node_cls)
                     for label in results_list])
     else:
         msg = "Unable to get labels"
         try:
             msg += ": " + response.json().get('message')
         except (ValueError, AttributeError, KeyError):
             pass
         raise StatusException(response.status_code, msg)
Пример #10
0
 def request(self, return_type):
     try:
         return self._cache[return_type]
     except KeyError:
         url = self._endpoint.replace("{returnType}", return_type)
         response = Request(**self._auth).post(url, data=self._data)
         if response.status_code == 200:
             results_list = response.json()
             self._cache[return_type] = results_list
             return results_list
         elif response.status_code == 404:
             raise NotFoundError(response.status_code,
                                 "Node or relationship not found")
         raise StatusException(response.status_code, "Invalid data sent")
Пример #11
0
 def rollback(self):
     if self.url_tx:
         request = Request(**self._class._auth)
         response = request.delete(self.url_tx)
         if response.status_code in [200, 201]:
             self._manage_errors(response.json()["errors"])
             self.finished = True
             for reference in self.executed:
                 obj = reference["obj"]
                 if obj is not None:
                     obj._elements = []
                     obj.columns = None
             self.executed = []
         else:
             raise TransactionException(response.status_code)
Пример #12
0
 def rollback(self):
     if self.url_tx:
         request = Request(**self._class._auth)
         response = request.delete(self.url_tx)
         if response.status_code in [200, 201]:
             self._manage_errors(response.json()["errors"])
             self.finished = True
             for reference in self.executed:
                 obj = reference["obj"]
                 if obj is not None:
                     obj._elements = []
                     obj.columns = None
             self.executed = []
         else:
             raise TransactionException(response.status_code)
Пример #13
0
 def new_request(self):
     # Newer versions of neo4jrestclient support auth more robustly
     # the older versions do not support at all, so we have to check here
     try:
         auth = self._auth
     except AttributeError:
         auth = {}
     return Request(**auth)
Пример #14
0
def degree(right, left, connection):
    lookup = Q('name', exact=right)
    start = neo.nodes.filter(lookup)[-1]

    lookup2 = Q('name', exact=left)
    end = neo.nodes.filter(lookup2)[-1]

    r = Request()
    d = {
        "to" : "http://localhost:7474/db/data/node/%s" % end.id,
        "max_depth" : 30,
        "relationships" : {
            "type" : connection,
            "direction" : "out"
        },
        "algorithm" : "shortestPath"
    }
    
    response, content = r.post("http://localhost:7474/db/data/node/%s/paths" % start.id, d)    
    print response, content, d

    content = json.loads(content)   
    if len(content) == 0:
        return []
    
    objs = []
    last = len(content[0]['nodes'])
    nodes = content[0]['nodes']
    relationships = content[0]['relationships']
    
    for k, v in enumerate(nodes):
        objs.append(Node(v))
        if(k != last - 1):
            objs.append(Relationship(relationships[k]))
            
    return objs