def benchmark(iterations, scale):
    """
    Deserialize a string C{iterations} times.  Make the string longer based
    on C{scale}.

    Prints the mean time per parse call.
    """
    s = serialize(BASE * scale)
    before = time()
    for i in xrange(iterations):
        parse(s)
    after = time()
    print (after - before) / iterations, 'per call'
def benchmark(iterations, scale):
    """
    Deserialize a string C{iterations} times.  Make the string longer based
    on C{scale}.

    Prints the mean time per parse call.
    """
    s = serialize(BASE * scale)
    before = time()
    for i in range(iterations):
        parse(s)
    after = time()
    print((after - before) / iterations, 'per call')
 def testRoundtrip(self):
     for struct in TEST_OBJECTS:
         bytes = json.serialize(struct)
         unstruct = json.parse(bytes)
         self.assertEquals(
             unstruct, struct, "Failed to roundtrip %r: %r (through %r)" %
             (struct, unstruct, bytes))
 def testStringlikeRountrip(self):
     for struct in TEST_STRINGLIKE_OBJECTS:
         bytes = json.serialize(struct)
         unstruct = json.parse(bytes)
         failMsg = "Failed to roundtrip %r: %r (through %r)" % (
             struct, unstruct, bytes)
         self.assertEquals(unstruct, struct, failMsg)
         self.assert_(isinstance(unstruct, unicode), failMsg)
Exemple #5
0
 def testRoundtrip(self):
     for struct in TEST_OBJECTS:
         bytes = json.serialize(struct)
         unstruct = json.parse(bytes)
         self.assertEquals(
             unstruct, struct,
             "Failed to roundtrip %r: %r (through %r)" % (
                 struct, unstruct, bytes))
Exemple #6
0
 def testStringlikeRountrip(self):
     for struct in TEST_STRINGLIKE_OBJECTS:
         bytes = json.serialize(struct)
         unstruct = json.parse(bytes)
         failMsg = "Failed to roundtrip %r: %r (through %r)" % (
                 struct, unstruct, bytes)
         self.assertEquals(unstruct, struct, failMsg)
         self.assert_(isinstance(unstruct, unicode), failMsg)
Exemple #7
0
    def renderHTTP(self, ctx):
        req = inevow.IRequest(ctx)
        try:
            d = self.livePage.addTransport(req)
        except defer.QueueOverflow:
            log.msg("Fast transport-close path")
            d = defer.succeed('')
        args = req.args.get('args', [()])[0]
        if args != ():
            args = json.parse(args)
        kwargs = req.args.get('kw', [{}])[0]
        if kwargs != {}:
            args = json.parse(kwargs)
        method = getattr(self, 'action_' + req.args['action'][0])
        method(ctx, *args, **kwargs)

        return d.addCallback(self._cbRender)
Exemple #8
0
 def testStringlikeRoundtrip(self):
     for struct in TEST_STRINGLIKE_OBJECTS:
         serialised = json.serialize(struct)
         deserialised = json.parse(serialised)
         failMsg = "Failed to roundtrip %r: %r (through %r)" % (
             struct, deserialised, serialised)
         self.assertEqual(deserialised, struct, failMsg)
         self.assertTrue(isinstance(deserialised, compat.unicode), failMsg)
Exemple #9
0
 def process(x, service):
     data, status, content = x
     if status != 200:
         log.msg(
             "got status code %d when querying service %s for request %r" %
             (status, service, requests))
         return
     if not content.startswith("application/json;"):
         log.msg("got content type %r when querying service %s for request %r" %
                 (content, service, requests))
         return
     results.append(json.parse(data))
Exemple #10
0
        def line(queryName, label):
            ret = json.parse((yield getPage(
                "http://bigasterisk.com/magma/light/state?name=%s" % queryName,
                headers={'x-identity-forward': 'secret-8-' + self.identity})))

            currently = ret['value']
            returnValue(
                T.form(method="POST", action="light/state")
                [T.input(type="hidden", name="name", value=queryName),
                 T.div[label, " ", T.span[currently], ", turn ",
                       T.input(type="submit",
                               name="value",
                               value="off" if currently == 'on' else "on")]])
Exemple #11
0
 def process(x, service):
     data, status, content = x
     if status != 200:
         log.msg(
             "got status code %d when querying service %s for request %r"
             % (status, service, requests))
         return
     if not content.startswith("application/json;"):
         log.msg(
             "got content type %r when querying service %s for request %r"
             % (content, service, requests))
         return
     results.append(json.parse(data))
Exemple #12
0
    def child_currentPlaylist(self, ctx):
        req = inevow.IRequest(ctx)
        if req.method in "PUT":
            playlist = postDataFromCtx(ctx)
            if playlist.startswith("{"):
                # preferred mode sends json
                playlist = json.parse(playlist)['name'].encode('utf8')

            if not playlist:
                raise ValueError("need name=playlist")
            return self.mpd.clear().addCallback(
                lambda result: self.mpd.load(playlist))
        else:
            raise NotImplementedError
Exemple #13
0
    def renderHTTP(self, ctx):
        req = inevow.IRequest(ctx)
        neverEverCache(req)
        if self.useActiveChannels:
            activeChannel(req)

        requestContent = req.content.read()
        messageData = json.parse(requestContent)

        response = self.messageDeliverer.basketCaseReceived(ctx, messageData)
        response.addCallback(json.serialize)
        req.notifyFinish().addErrback(
            lambda err: self.messageDeliverer.
            _unregisterDeferredAsOutputChannel(response))
        return response
Exemple #14
0
 def add(service, date, data):
     lbs, status, content = data
     if status != 200:
         log.msg("service %s responded error %s" % (service, status))
         return
     if not content.startswith("application/json;"):
         log.msg("service %s did not answer with JSON (%s)" % content)
         return
     lbs = json.parse(lbs)
     for lb in lbs:
         if lb in self.newloadbalancers[date]:
             self.newloadbalancers[date][lb].append(service)
             self.newloadbalancers[date][lb].sort()
         else:
             self.newloadbalancers[date][lb] = [service]
     self.updated[date] = time.time()
Exemple #15
0
 def add(service, date, data):
     lbs, status, content = data
     if status != 200:
         log.msg("service %s responded error %s" % (service, status))
         return
     if not content.startswith("application/json;"):
         log.msg("service %s did not answer with JSON (%s)" % content)
         return
     lbs = json.parse(lbs)
     for lb in lbs:
         if lb in self.newloadbalancers[date]:
             self.newloadbalancers[date][lb].append(service)
             self.newloadbalancers[date][lb].sort()
         else:
             self.newloadbalancers[date][lb] = [service]
     self.updated[date] = time.time()
Exemple #16
0
 def child_setMusicState(self, ctx):
     """
     post a json object from a getMusicState call. The current
     playlist will be cleared and replaced with the input
     one. Playback will pick up where the input says to
     """
     data = json.parse(postDataFromCtx(ctx))
     yield self.mpd.clear()
     startNum = None
     for num, row in enumerate(data['playlist']):
         yield self.mpd.add(row['file'].encode('utf-8'))
         if row['Id'] == data['status']['songid']:
             startNum = num
     if startNum is not None and data['status']['state'] == 'play':
         yield self.mpd.seek(int(data['status']['time'].split(':')[0]),
                             startNum)
     defer.returnValue('ok')
Exemple #17
0
        def line(queryName, label):
            ret = json.parse(
                (
                    yield getPage(
                        "http://bigasterisk.com/magma/light/state?name=%s" % queryName,
                        headers={"x-identity-forward": "secret-8-" + self.identity},
                    )
                )
            )

            currently = ret["value"]
            returnValue(
                T.form(method="POST", action="light/state")[
                    T.input(type="hidden", name="name", value=queryName),
                    T.div[
                        label,
                        " ",
                        T.span[currently],
                        ", turn ",
                        T.input(type="submit", name="value", value="off" if currently == "on" else "on"),
                    ],
                ]
            )
Exemple #18
0
def argsFromPostOrGet(method, postData, ctx):
    """return an args dict based on the json-encoded postdata (or form urlencoded),
    considering only args that the method callable accepts"""
    postArgs = {}
    if postData:

        if inevow.IRequest(ctx).getHeader('Content-Type').startswith("application/x-www-form-urlencoded"):
            postArgs = dict(urlparse.parse_qsl(postData))
        else:
            postArgs = json.parse(postData)
    acceptedArgs, _, _, _ = inspect.getargspec(method)
    callArgs = {}
    for name in acceptedArgs:
        if name == 'self':
            continue
        if name in postArgs:
            v = postArgs[name]
            if isinstance(v, unicode):
                v = v.encode('utf-8')
            callArgs[name] = v
        elif ctx.arg(name):
            callArgs[name] = ctx.arg(name)
    return callArgs
Exemple #19
0
 def testEscapedControls(self):
     self.assertEquals(
         json.parse('"\\f\\b\\n\\t\\r"'),
         u"\f\b\n\t\r")
Exemple #20
0
 def test_undefined(self):
     """
     C{undefined} is parsed as Python C{None}.
     """
     self.assertEqual(None, json.parse(b'undefined'))
Exemple #21
0
    def child_saveStatements(self, ctx):
        content = inevow.IRequest(ctx).content
        content.seek(0)
        stmts = json.parse(content.read())

        return writeStatements(statementsFromJsRdf(stmts))
Exemple #22
0
 def test_undefined(self):
     """
     C{undefined} is parsed as Python C{None}.
     """
     self.assertEquals(None, json.parse(b'undefined'))
Exemple #23
0
 def testHexEscapedCodepoints(self):
     self.assertEqual(json.parse('"\\xe1\\xe9\\xed\\xf3\\xfa\\xfd"'),
                      u"\u00e1\u00e9\u00ed\u00f3\u00fa\u00fd")
Exemple #24
0
 def testScientificNotation(self):
     self.assertEquals(json.parse('1e10'), 10**10)
     self.assertEquals(json.parse('1e0'), 1)
Exemple #25
0
 def testHexEscapedCodepoints(self):
     self.assertEquals(
         json.parse('"\\xe1\\xe9\\xed\\xf3\\xfa\\xfd"'),
         u"\xe1\xe9\xed\xf3\xfa\xfd")
 def testScientificNotation(self):
     self.assertEquals(json.parse('1e10'), 10**10)
     self.assertEquals(json.parse('1e0'), 1)
 def testEscapedControls(self):
     self.assertEquals(json.parse('"\\f\\b\\n\\t\\r"'), u"\f\b\n\t\r")
 def testHexEscapedCodepoints(self):
     self.assertEquals(json.parse('"\\xe1\\xe9\\xed\\xf3\\xfa\\xfd"'),
                       u"\xe1\xe9\xed\xf3\xfa\xfd")