Beispiel #1
0
    def finish(self, value, request):
        request.setHeader("Content-Type", "application/json; charset=UTF-8")
        if isinstance(value, Failure):
            err = value.value
            if self.debug:
                print "-" * 30, "TRACEKBACK", "-" * 30
                value.printTraceback()
                print "^" * 30, "TRACEKBACK", "^" * 30
            request.setResponseCode(500)
            if isinstance(err, backend.ValidationError):
                request.setResponseCode(400)
            elif isinstance(err, backend.NodeNotFound):
                request.setResponseCode(404)
            elif isinstance(err, backend.NodeInUseError):
                request.setResponseCode(400)
            elif isinstance(err, backend.EmptyInputData):
                request.setResponseCode(400)
            elif isinstance(err, backend.BatchOperationError):
                request.setResponseCode(400)
            elif isinstance(err, Exception) and not isinstance(err, backend.GenericError):
                err = dict(error="UnknownError", message=err.message)
            request.write(json_encode(dict(err)) + "\n")
        else:
            request.setResponseCode(200)
            request.write(json_encode(value) + "\n")

        info("respone time: %.3fms" % ((time.time() - self.startTime) * 1000))
        request.finish()
Beispiel #2
0
    def finish(self, value, request):
        log.msg("finish value = %s" % str(value), level=logging.DEBUG)
        request.setHeader('Content-Type', 'application/json;charset=UTF-8')
        if isinstance(value, Failure):
            err = value.value
            request.setResponseCode(500)
            error = dict(error="unknown error occurred")
            if isinstance(err, defer.CancelledError):
                log.msg("Request cancelled.", level=logging.DEBUG)
                return None
            elif isinstance(err, minitree.db.NodeNotFound):
                request.setResponseCode(404)
                error = dict(error="node not found", message=err.message,
                             instance="db.NodeNotFound")
            elif isinstance(err, minitree.db.ParentNotFound):
                request.setResponseCode(400)
                error = dict(error="parent node not found",
                             message=err.message,
                             instance="db.ParentNotFound")
            elif isinstance(err, minitree.db.PathDuplicatedError):
                request.setResponseCode(400)
                error = dict(error=str(err),
                             instance="db.PathDuplicatedError")
            elif isinstance(err, minitree.db.PathError):
                request.setResponseCode(400)
                error = dict(error=str(err),
                             instance="db.PathError")
            elif isinstance(err, minitree.db.DataTypeError):
                request.setResponseCode(400)
                error = dict(error=str(err),
                             instance="db.DataTypeError")
            elif isinstance(err, InvalidInputData):
                request.setResponseCode(400)
                error = dict(error=str(err),
                             instance="service.NodeSerivce.InvalidInputData")
            elif isinstance(err, ValueError):
                request.setResponseCode(400)
                error = dict(error=str(err), instance="ValueError")
            elif isinstance(err, ServiceAuthenticationError):
                request.setResponseCode(403)
                error = dict(error="forbidden",
                             message=str(err),
                             instance="service.NodeService."
                             "ServiceAuthenticationError")
            elif isinstance(err, UnicodeDecodeError):
                request.setResponseCode(400)
                error = dict(error=str(err),
                             instance="UnicodeDecodeError")
            request.write(json_encode(error) + "\n")
        else:
            request.setResponseCode(200)
            request.write(json_encode(value) + "\n")

        log.msg("respone time: %.3fms" % (
                (time.time() - self.startTime) * 1000))
        request.finish()
Beispiel #3
0
    def finish(self, value, request):
        request.setHeader('Content-Type', 'application/json; charset=UTF-8')
        if isinstance(value, Failure):
            err = value.value
            request.setResponseCode(500)
            error = dict(error="generic", message=str(err))
            request.write(json_encode(error) + "\n")
        else:
            request.setResponseCode(200)
            request.write(json_encode(value) + "\n")

        info("respone time: %.3fms" % ((time.time() - self.startTime) * 1000))
        request.finish()
 def test_json_schema_without_header(self):
     data = json_encode(dict(name='john', age=20))
     response = self.fetch('/json',
                           method='POST',
                           body=data,
                           raise_error=False)
     assert response.code == 500
Beispiel #5
0
    def _dispatch(self, h, user, channel, text=""):

        if "text" in h:
            users, channels = self._default_target(user, channel)
            text = self._expandvar(h["text"], self.context)
            reply = dict(users=users, channels=channels,
                         text=text.splitlines())
            d = defer.succeed(reply)
            d.addBoth(self._handled)

        if "http" in h:
            postdata = json_encode(dict(servername=self.servername,
                                        user=user,
                                        channel=channel,
                                        context=self.context,
                                        text=text))
            d = getPage(h["http"], method="POST", postdata=postdata)
            d.addCallback(self._http_done, user, channel)
            d.addBoth(self._handled)

        if "builtin" in h:
            d = threads.deferToThread(self._execute_builtin, h,
                                      user, channel, text)
            d.addBoth(self._handled)

        if "redirect" in h:
            d = self._redirect_rewrite(h, text)
            d.addBoth(lambda x:
                      threads.deferToThread(self._redirect,
                                            x, h, user, channel, text))
Beispiel #6
0
    async def publish(self, content: Any):
        if not hasattr(self, "active_exchange"):
            raise JSONQueueError("no active exchange set")

        message = Message(bytes(json_encode(content), "utf-8"),
                          content_type="application/json")
        await self.active_exchange.publish(message, self.routing_key)
Beispiel #7
0
    async def publish(self, content: Any):
        if not hasattr(self, 'active_exchange'):
            raise JSONQueueError('no active exchange set')

        message = Message(bytes(json_encode(content), 'utf-8'),
                          content_type='application/json')
        await self.active_exchange.publish(message, self.routing_key)
Beispiel #8
0
 def test_json_request(self):
     data = json_encode(dict(x=1, y=2))
     headers = {
         'Content-Type': 'application/json',
     }
     response = self.fetch('/', method='POST', body=data, headers=headers)
     assert response.body == b'{"data":{"x":1,"y":2}}'
Beispiel #9
0
 def test_json_request_no_content_type(self):
     data = json_encode(dict(x=1, y=2))
     headers = {
         'Content-Type': '',
     }
     response = self.fetch('/', method='POST', body=data, headers=headers)
     assert response.body == b'{"data":{}}'
Beispiel #10
0
 def test_get_data_empty(self):
     data = json_encode(dict(non='hello, world'))
     headers = {
         'Content-Type': 'application/json',
     }
     response = self.fetch('/', method='PUT', body=data, headers=headers)
     assert response.body == b'{"quote":"no data"}'
Beispiel #11
0
 def test_get_data_dont_strip(self):
     data = json_encode(dict(quote='\t\r\n vvv  \r\t\n  '))
     headers = {
         'Content-Type': 'application/json',
     }
     response = self.fetch('/', method='PATCH', body=data, headers=headers)
     assert response.body == b'{"quote":"\\t\\r\\n vvv  \\r\\t\\n  "}'
Beispiel #12
0
    def doResponse(self, value, request):
        request.setHeader("Content-Type", "application/json; charset=UTF-8")
        if isinstance(value, Failure):
            reply = dict(error=str(value.value),
                         traceback=value.getTraceback())
            request.setResponseCode(500)
            request.write(json_encode(reply))

        else:
            request.setResponseCode(200)
            request.write(json_encode(value))

        log.msg("respone time: %.3fms" % (
            (time.time() - self.startTime) * 1000), level=DEBUG)

        request.finish()
Beispiel #13
0
 def test_get_data_num(self):
     data = json_encode(dict(quote=1984))
     headers = {
         'Content-Type': 'application/json',
     }
     response = self.fetch('/', method='PUT', body=data, headers=headers)
     assert response.body == b'{"quote":1984}'
Beispiel #14
0
    def _dispatch(self, h, user, channel, text=""):

        if "text" in h:
            users, channels = self._default_target(user, channel)
            text = self._expandvar(h["text"], self.context)
            reply = dict(users=users,
                         channels=channels,
                         text=text.splitlines())
            d = defer.succeed(reply)
            d.addBoth(self._handled)

        if "http" in h:
            postdata = json_encode(
                dict(servername=self.servername,
                     user=user,
                     channel=channel,
                     context=self.context,
                     text=text))
            d = getPage(h["http"], method="POST", postdata=postdata)
            d.addCallback(self._http_done, user, channel)
            d.addBoth(self._handled)

        if "builtin" in h:
            d = threads.deferToThread(self._execute_builtin, h, user, channel,
                                      text)
            d.addBoth(self._handled)

        if "redirect" in h:
            d = self._redirect_rewrite(h, text)
            d.addBoth(lambda x: threads.deferToThread(self._redirect, x, h,
                                                      user, channel, text))
Beispiel #15
0
    def finish(self, value, request):
        if isinstance(value, Failure):
            error = value.value
            if isinstance(error, ServiceError):
                request.setResponseCode(error.code)
                message = error.message
                if isinstance(message, dict):
                    message["traceback"] = value.getTraceback()
                elif isinstance(message, str):
                    message += value.getTraceback()
            else:
                request.setHeader("Content-Type", "text/plain; charset=UTF-8")
                request.setResponseCode(500)
                message = "500 Internal Server Error: UNKNOWN\n"
                message += value.getTraceback()
        else:
            message = value

        if isinstance(message, dict):
            request.write(json_encode(message))
        elif isinstance(message, str):
            request.write(message)
        else:
            request.setResponseCode(500)
            request.write("500 Internal Server Error: Invalid Content Type")

        request.finish()

        debug("response latency: %.3fms" % \
              (time.time() - self.__startTime__) * 1000)
 def test_json_schema(self):
     data = json_encode(dict(name='john', age=20))
     headers = {
         'Content-Type': 'application/json',
     }
     response = self.fetch('/json',
                           method='POST',
                           body=data,
                           headers=headers)
     assert response.code == 200
Beispiel #17
0
def encode(data, secret=None):

    # Remove trailling padding characters for convenience (been URI encoded).
    json_data = json_encode(data)
    sign = str(_hmac(json_data, secret), 'UTF-8').rstrip('=')
    raw = _pad(json_data)
    iv = Random.new().read(AES.block_size)
    cipher = AES.new(_key(secret), AES.MODE_CBC, iv)
    enc = str(b64encode(iv + cipher.encrypt(raw)), 'UTF-8').rstrip('=')
    return f'{enc}.{sign}'
Beispiel #18
0
    def finish(self, value, request):
        request.setHeader('Content-Type', 'application/json; charset=UTF-8')
        if isinstance(value, Failure):
            err = value.value
            request.setResponseCode(500)
            if isinstance(err, ArgumentError):
                error = dict(error="argument", message=str(err))
            elif isinstance(err, backend.SearchGrammarError):
                error = dict(error="syntax", message=str(err),
                             traceback=value.getTraceback())
            elif isinstance(err, ParseError):
                error = dict(error="syntax", message=str(err))
            else:
                error = dict(error="generic", message=str(err),
                             traceback=value.getTraceback())
            request.write(json_encode(error) + "\n")
        else:
            request.setResponseCode(200)
            request.write(json_encode(value) + "\n")

        log.msg("respone time: %.3fms" % (
                (time.time() - self.startTime) * 1000))
        request.finish()
Beispiel #19
0
    def finalize(self, value, request):

        if isinstance(value, Failure):
            request.setResponseCode(500)
            response = dict(success=False,
                            reason=value.getErrorMessage(),
                            traceback=value.getTraceback())
        else:
            response = value
            request.setResponseCode(200)

        if isinstance(response, str):
            request.write(response)
        elif isinstance(response, unicode):
            request.write(response.decode('UTF-8'))
        else:
            request.setHeader('Content-Type',
                              'application/json; charset=UTF-8')
            request.write(json_encode(response))

        request.finish()
Beispiel #20
0
    def finalize(self, result, request):
        from os import getpid

        request.setHeader('Content-Type', 'application/json; charset=UTF-8')

        if isinstance(result, Failure):
            request.setResponseCode(500)
            if isinstance(result.value, exception.AlmarErrorBase):
                error = dict(message=str(result.value), pid=getpid())
                response = dict(error=error)
            else:
                error = dict(data=result.getTraceback(),
                             message=str(result.value),
                             pid=getpid())
                response = dict(error=error)
        else:
            response = result.content
            request.setResponseCode(result.code)

        request.write(json_encode(response))
        if not request._disconnected:
            request.finish()
Beispiel #21
0
    def write_cdx_line(self, out, entry, filename):
        out.write(entry['urlkey'])
        out.write(' ')
        out.write(entry['timestamp'])
        out.write(' ')

        outdict = OrderedDict()

        for n, v in entry.iteritems():
            if n in ('urlkey', 'timestamp'):
                continue

            if n.startswith('_'):
                continue

            if not v or v == '-':
                continue

            outdict[n] = v

        outdict['filename'] = filename
        out.write(json_encode(outdict))
        out.write('\n')
Beispiel #22
0
 def bail(self, status_code: int, *args, **kwargs):
     self.set_header('Content-Type', 'application/json; charset=UTF-8')
     self.set_status(status_code)
     self.finish(json_encode(kwargs))
Beispiel #23
0
 def reply(self, *args, **kwargs):
     self.set_header('Content-Type', 'application/json; charset=UTF-8')
     self.finish(json_encode(kwargs))