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)
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)
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
def _request(self, method, url, data={}, headers={}): splits = urlparse(url) if splits.port: port = u":%s" % splits.port else: port = u"" if splits.query and splits.fragment: root_uri = "%s://%s%s%s?%s#%s" % (splits.scheme, splits.hostname, port, splits.path, splits.query, splits.fragment) elif splits.query: root_uri = "%s://%s%s%s?%s" % (splits.scheme, splits.hostname, port, splits.path, splits.query) elif splits.fragment: root_uri = "%s://%s%s%s#%s" % (splits.scheme, splits.hostname, port, splits.path, splits.fragment) else: root_uri = "%s://%s%s%s" % (splits.scheme, splits.hostname, port, splits.path) username = splits.username or self.username password = splits.password or self.password cert = None if self.cert_file: if self.key_file: cert = (self.cert_file, self.key_file) else: cert = self.cert_file headers = headers or {} headers['Accept'] = 'application/json; charset=UTF-8' headers['Accept-Encoding'] = '*' headers['Accept-Charset'] = 'UTF-8,ISO-8859-1;q=0.7,*;q=0.7' headers['Connection'] = 'keep-alive' if not options.CACHE: headers['Cache-Control'] = 'no-cache' headers['User-Agent'] = 'neo4jrestclient/%s ' % __version__ auth = None if username and password: auth = (username, password) if method in ("POST", "PUT"): headers['Content-Type'] = 'application/json' data = self._json_encode(data, ensure_ascii=True) verify = options.VERIFY_SSL try: method = method.lower() response = getattr(session, method)(root_uri, headers=headers, data=data, cert=cert, auth=auth, verify=verify) if response.status_code == 401: raise StatusException(401, "Authorization Required") return response except AttributeError: raise Exception("Unknown error. Is the server running?")
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")
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)
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")
def test_status_exception_params(self): StatusException(402, "Message")