Exemple #1
0
 def _delete(self, url):
     try:
         return self.http_pool.request(method="DELETE",
                                       url=url,
                                       headers=dict(self.headers))
     except HTTPError as error:
         raise_from(ProtocolError("Failed to DELETE %r" % url), error)
Exemple #2
0
 def from_json(cls, status, data):
     try:
         content = json_loads(data, object_hook=JSONHydrant.json_to_packstream)
     except ValueError as error:
         raise_from(ProtocolError("Cannot decode response content as JSON"), error)
     else:
         return cls(status, content)
Exemple #3
0
 def _hello(self):
     self._assert_open()
     extra = {"scheme": "basic",
              "principal": self.profile.user,
              "credentials": self.profile.password}
     clean_extra = dict(extra)
     clean_extra.update({"credentials": "*******"})
     log.debug("[#%04X] C: INIT %r %r", self.local_port, self.user_agent, clean_extra)
     response = self._write_request(0x01, self.user_agent, extra, vital=True)
     self._send()
     self._fetch()
     self._audit(response)
     self.connection_id = response.metadata.get("connection_id")
     self.server_agent = response.metadata.get("server")
     if not self.server_agent.startswith("Neo4j/"):
         raise ProtocolError("Unexpected server agent {!r}".format(self.server_agent))
Exemple #4
0
 def read_message_py2(self):
     chunks = []
     while True:
         hi, lo = self.wire.read(2)
         if hi == lo == 0:
             break
         size = hi << 8 | lo
         chunks.append(self.wire.read(size))
     message = bytearray(b"".join(map(bytes, chunks)))
     _, n = divmod(message[0], 0x10)
     try:
         unpacker = UnpackStream(message, offset=2)
         fields = [unpacker.unpack() for _ in range(n)]
     except ValueError as error:
         raise_from(ProtocolError("Bad message content"), error)
     else:
         return message[1], fields
Exemple #5
0
    def _fetch(self):
        """ Fetch and process the next incoming message.

        This method does not raise an exception on receipt of a
        FAILURE message. Instead, it sets the response (and
        consequently the parent query and transaction) to a failed
        state. It is the responsibility of the caller to convert this
        failed state into an exception.
        """
        rs = self._responses[0]
        tag, fields = self._reader.read_message()
        if tag == 0x70:
            log.debug("[#%04X] S: SUCCESS %s", self.local_port,
                      " ".join(map(repr, fields)))
            rs.set_success(**fields[0])
            self._responses.popleft()
            self._metadata.update(fields[0])
        elif tag == 0x71:
            # If a RECORD is received, check for more records
            # in the buffer immediately following, and log and
            # add them all at the same time
            while self._reader.peek_message() == 0x71:
                _, extra_fields = self._reader.read_message()
                fields.extend(extra_fields)
            more = len(fields) - 1
            log.debug("[#%04X] S: RECORD %r%s", self.local_port, fields[0],
                      " (...and %d more)" % more if more else "")
            rs.add_records(fields)
        elif tag == 0x7F:
            log.debug("[#%04X] S: FAILURE %s", self.local_port,
                      " ".join(map(repr, fields)))
            rs.set_failure(**fields[0])
            self._responses.popleft()
            if rs.vital:
                self._wire.close()
            else:
                self.reset(force=True)
        elif tag == 0x7E and not rs.vital:
            log.debug("[#%04X] S: IGNORED", self.local_port)
            rs.set_ignored()
            self._responses.popleft()
        else:
            log.debug("[#%04X] S: (Unexpected protocol message #%02X)",
                      self.local_port, tag)
            self._wire.close()
            raise ProtocolError("Unexpected protocol message #%02X", tag)
Exemple #6
0
 def _post(self, url, statement=None, parameters=None):
     if statement:
         statements = [
             OrderedDict([
                 ("statement", statement),
                 ("parameters", dehydrate(parameters or {})),
                 ("resultDataContents", ["REST"]),
                 ("includeStats", True),
             ])
         ]
     else:
         statements = []
     try:
         return self.http_pool.request(method="POST",
                                       url=url,
                                       headers=dict(self.headers, **{"Content-Type": "application/json"}),
                                       body=json_dumps({"statements": statements}))
     except HTTPError as error:
         raise_from(ProtocolError("Failed to POST to %r" % url), error)
Exemple #7
0
 def read_message(self):
     chunks = []
     while True:
         try:
             hi, lo = self.wire.read(2)
         except WireError as error:
             raise_from(ConnectionBroken("Failed to read message"), error)
         else:
             if hi == lo == 0:
                 break
             size = hi << 8 | lo
             chunks.append(self.wire.read(size))
     message = b"".join(chunks)
     _, n = divmod(message[0], 0x10)
     try:
         unpacker = UnpackStream(message, offset=2)
         fields = [unpacker.unpack() for _ in range(n)]
     except ValueError as error:
         raise_from(ProtocolError("Bad message content"), error)
     else:
         return message[1], fields