Python ujson.dumps() Examples

The following are code examples for showing how to use ujson.dumps(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: swaggerit   Author: dutradda   File: test_method_errors.py    MIT License 7 votes vote down vote up
def test_integrity_error_handling_with_foreign_key(self, post_method, stream, session):
        stream.feed_data(ujson.dumps([{'m2_id': 1}]).encode())
        stream.feed_eof()
        request = SwaggerRequest('/model1/', 'post', body=stream, headers={'content-type': 'application/json'})
        resp = await post_method(request, session)

        assert resp.status_code == 400
        assert ujson.loads(resp.body) == {
            'params': {'m2_id': 1},
            'database message': {
                'message':  'Cannot add or update a child row: '
                            'a foreign key constraint fails '
                            '(`swaggerit_test`.`model1_swagger`, '
                            'CONSTRAINT `model1_swagger_ibfk_1` FOREIGN '
                            'KEY (`m2_id`) REFERENCES `model2_swagger` '
                            '(`id`))',
                'code': 1452
            }
        } 
Example 2
Project: swaggerit   Author: dutradda   File: test_method_errors.py    MIT License 7 votes vote down vote up
def test_model_base_error_handling_with_patch_and_with_nested_remove(self, patch_method, post_method, stream, session):
        stream.feed_data(b'[{}]')
        stream.feed_eof()
        request = SwaggerRequest('/model1/1/', 'patch', body=stream, headers={'content-type': 'application/json'})
        await post_method(request, session)

        stream = asyncio.StreamReader(loop=session.loop)
        body = {'model2_': {'id': 1, '_operation': 'remove'}}
        stream.feed_data(ujson.dumps(body).encode())
        stream.feed_eof()
        request = SwaggerRequest('/model1/1/', 'patch', path_params={'id': 1}, body=stream, headers={'content-type': 'application/json'})
        resp = await patch_method(request, session)

        assert resp.status_code == 400
        assert ujson.loads(resp.body) == {
            'instance': [body],
            'message': "Can't execute nested 'remove' operation"
        } 
Example 3
Project: swaggerit   Author: dutradda   File: test_method_errors.py    MIT License 7 votes vote down vote up
def test_model_base_error_handling_with_patch_and_with_nested_update(self, patch_method, post_method, stream, session):
        stream.feed_data(b'[{}]')
        stream.feed_eof()
        request = SwaggerRequest('/model1/1/', 'patch', body=stream, headers={'content-type': 'application/json'})
        await post_method(request, session)

        stream = asyncio.StreamReader(loop=session.loop)
        body = {'model2_': {'id': 1, '_operation': 'update'}}
        stream.feed_data(ujson.dumps(body).encode())
        stream.feed_eof()
        request = SwaggerRequest('/model1/1/', 'patch', path_params={'id': 1}, body=stream, headers={'content-type': 'application/json'})
        resp = await patch_method(request, session)

        assert resp.status_code == 400
        assert ujson.loads(resp.body) == {
            'instance': [body],
            'message': "Can't execute nested 'update' operation"
        } 
Example 4
Project: swaggerit   Author: dutradda   File: test_session_integration.py    MIT License 7 votes vote down vote up
def test_if_two_commits_sets_redis_with_two_models_correctly(
            self, session, redis):
        session.add(await Model10.new(session, id=1))
        session.add(await Model11.new(session, id=1))
        await session.commit()

        assert await redis.hgetall(Model10.__key__) == {
            b'1': ujson.dumps({b'id': 1}).encode()
        }
        assert await redis.hgetall(Model11.__key__) == {
            b'1': ujson.dumps({b'id': 1}).encode()
        }

        session.add(await Model10.new(session, id=2))
        session.add(await Model11.new(session, id=2))
        await session.commit()

        assert await redis.hgetall(Model10.__key__) == {
            b'1': ujson.dumps({b'id': 1}).encode(),
            b'2': ujson.dumps({b'id': 2}).encode()
        }
        assert await redis.hgetall(Model11.__key__) == {
            b'1': ujson.dumps({b'id': 1}).encode(),
            b'2': ujson.dumps({b'id': 2}).encode()
        } 
Example 5
Project: wallet   Author: clayman74   File: __init__.py    MIT License 7 votes vote down vote up
def json_response(data, status: int = 200, **kwargs) -> web.Response:
    return web.json_response(data, dumps=ujson.dumps, status=status, **kwargs) 
Example 6
Project: swaggerit   Author: dutradda   File: test_session_integration.py    MIT License 6 votes vote down vote up
def test_if_two_instance_are_deleted_from_redis(self, session, redis):
        inst1 = await Model10.new(session, id=1)
        inst2 = await Model10.new(session, id=2)
        session.add_all([inst1, inst2])
        await session.commit()

        assert await redis.hgetall(Model10.__key__) == {
            b'1': ujson.dumps({b'id': 1}).encode(),
            b'2': ujson.dumps({b'id': 2}).encode()
        }

        session.delete(inst1)
        session.delete(inst2)
        await session.commit()

        assert await redis.hgetall(Model10.__key__) == {} 
Example 7
Project: swaggerit   Author: dutradda   File: test_session_integration.py    MIT License 6 votes vote down vote up
def test_if_two_commits_delete_redis_correctly(self, session, redis):
        inst1 = await Model10.new(session, id=1)
        inst2 = await Model10.new(session, id=2)
        session.add_all([inst1, inst2])
        await session.commit()

        assert await redis.hgetall(Model10.__key__) == {
            b'1': ujson.dumps({b'id': 1}).encode(),
            b'2': ujson.dumps({b'id': 2}).encode()
        }

        session.delete(inst1)
        await session.commit()

        assert await redis.hgetall(Model10.__key__) == {
            b'2': ujson.dumps({b'id': 2}).encode()
        }

        session.delete(inst2)
        await session.commit()

        assert await redis.hgetall(Model10.__key__) == {} 
Example 8
Project: swaggerit   Author: dutradda   File: method.py    MIT License 6 votes vote down vote up
def _valdation_error_to_response(self, error, headers):
        if error.absolute_path or error.absolute_schema_path:
            message = '{}. Failed validating instance{} for schema{}'.format(
                error.message,
                self._format_error_path(error.absolute_path),
                self._format_error_path(error.absolute_schema_path)
            )
        else:
            message = error.message

        body = {
            'message': message
        }
        if isinstance(error.schema, dict) and len(error.schema):
            body['schema'] = error.schema
        if error.instance:
            body['instance'] = error.instance
        return SwaggerResponse(400, body=ujson.dumps(body), headers=headers) 
Example 9
Project: swaggerit   Author: dutradda   File: session.py    MIT License 6 votes vote down vote up
def _exec_hmset_dict(self, insts):
        models_keys_insts_keys_insts_map = defaultdict(dict)
        models_keys_insts_keys_map = defaultdict(set)

        for inst in insts:
            model = type(inst)
            if not model.__use_redis__:
                continue

            filters_names_set = await self._get_filters_names_set(inst)
            for filters_names in filters_names_set:
                model_redis_key = model.get_key(filters_names.decode())
                inst_redis_key = model.get_instance_key(inst)

                inst_old_redis_key = getattr(inst, 'old_redis_key', None)
                if inst_old_redis_key is not None and inst_old_redis_key != inst_redis_key:
                    models_keys_insts_keys_map[model_redis_key].add(inst_old_redis_key)

                models_keys_insts_keys_insts_map[model_redis_key][inst_redis_key] = ujson.dumps(inst.todict())

        for model_key, insts_keys_insts_map in models_keys_insts_keys_insts_map.items():
            await self.redis_bind.hmset_dict(model_key, insts_keys_insts_map)

        for model_key, insts_keys in models_keys_insts_keys_map.items():
            await self.redis_bind.hdel(model_key, *insts_keys) 
Example 10
Project: sanic   Author: huge-success   File: response.py    MIT License 6 votes vote down vote up
def json(
    body,
    status=200,
    headers=None,
    content_type="application/json",
    dumps=json_dumps,
    **kwargs
):
    """
    Returns response object with body in json format.

    :param body: Response data to be serialized.
    :param status: Response code.
    :param headers: Custom Headers.
    :param kwargs: Remaining arguments that are passed to the json encoder.
    """
    return HTTPResponse(
        dumps(body, **kwargs),
        headers=headers,
        status=status,
        content_type=content_type,
    ) 
Example 11
Project: monasca-events-api   Author: openstack   File: test_events_v1.py    Apache License 2.0 6 votes vote down vote up
def test_should_fail_missing_timestamp_in_body(self, bulk_processor):
        events_resource = _init_resource(self)
        events_resource._processor = bulk_processor
        unit_test_patch = os.path.dirname(__file__)
        json_file_path = 'event_template_json/req_simple_event.json'
        patch_to_req_simple_event_file = os.path.join(unit_test_patch,
                                                      json_file_path)
        with open(patch_to_req_simple_event_file, 'r') as fi:
            events = json.load(fi)['events']
        body = {'events': [events]}
        response = self.simulate_request(
            path=ENDPOINT,
            method='POST',
            headers={
                'Content-Type': 'application/json',
                'X_ROLES': 'monasca-user'
            },
            body=json.dumps(body)
        )
        self.assertEqual(falcon.HTTP_422, response.status) 
Example 12
Project: redis-marshal   Author: mitjafelicijan   File: bottle.py    MIT License 6 votes vote down vote up
def apply(self, callback, route):
        dumps = self.json_dumps
        if not self.json_dumps: return callback

        def wrapper(*a, **ka):
            try:
                rv = callback(*a, **ka)
            except HTTPResponse as resp:
                rv = resp

            if isinstance(rv, dict):
                #Attempt to serialize, raises exception on failure
                json_response = dumps(rv)
                #Set content type only if serialization successful
                response.content_type = 'application/json'
                return json_response
            elif isinstance(rv, HTTPResponse) and isinstance(rv.body, dict):
                rv.body = dumps(rv.body)
                rv.content_type = 'application/json'
            return rv

        return wrapper 
Example 13
Project: tomodachi   Author: kalaspuff   File: json_base.py    MIT License 6 votes vote down vote up
def build_message(cls, service: Any, topic: str, data: Any, **kwargs: Any) -> str:
        data_encoding = 'raw'
        if len(ujson.dumps(data)) >= 60000:
            data = base64.b64encode(zlib.compress(ujson.dumps(data).encode('utf-8'))).decode('utf-8')
            data_encoding = 'base64_gzip_json'

        message = {
            'service': {
                'name': getattr(service, 'name', None),
                'uuid': getattr(service, 'uuid', None)
            },
            'metadata': {
                'message_uuid': '{}.{}'.format(getattr(service, 'uuid', ''), str(uuid.uuid4())),
                'protocol_version': PROTOCOL_VERSION,
                'compatible_protocol_versions': ['json_base-wip'],  # deprecated
                'timestamp': time.time(),
                'topic': topic,
                'data_encoding': data_encoding
            },
            'data': data
        }
        return ujson.dumps(message) 
Example 14
Project: tomodachi   Author: kalaspuff   File: test_protocol.py    MIT License 6 votes vote down vote up
def test_json_base(monkeypatch: Any, capsys: Any, loop: Any) -> None:
    services, future = start_service('tests/services/dummy_service.py', monkeypatch)

    instance = services.get('test_dummy')

    async def _async() -> None:
        data = {'key': 'value'}
        t1 = time.time()
        json_message = await instance.message_protocol.build_message(instance, 'topic', data)
        t2 = time.time()
        result, message_uuid, timestamp = await instance.message_protocol.parse_message(json_message)
        assert result.get('data') == data
        assert result.get('metadata', {}).get('data_encoding') == 'raw'
        assert len(ujson.dumps(result.get('data'))) == len(ujson.dumps(data))
        assert ujson.dumps(result.get('data')) == ujson.dumps(data)
        assert len(message_uuid) == 73
        assert message_uuid[0:36] == instance.uuid
        assert timestamp >= t1
        assert timestamp <= t2

    loop.run_until_complete(_async())

    os.kill(os.getpid(), signal.SIGINT)
    loop.run_until_complete(future) 
Example 15
Project: tributary   Author: timkpaine   File: kafka.py    Apache License 2.0 6 votes vote down vote up
def AsyncKafka(foo, foo_kwargs=None, servers='', topic='', json=False, wrap=False):
    foo = _wrap(foo, foo_kwargs or {})

    p = Producer({'bootstrap.servers': servers})

    async def _send(foo, producer, topic, json, wrap):
        ret = []
        async for data in foo():
            # Trigger any available delivery report callbacks from previous produce() calls
            producer.poll(0)

            if wrap:
                data = [data]

            if json:
                data = ujson.dumps(data)

            producer.produce(topic, data.encode('utf-8'), callback=lambda *args: ret.append(args))

            for data in ret:
                yield data
            ret = []

    return _wrap(_send, dict(foo=foo, producer=p, topic=topic, json=json, wrap=wrap), name='Kafka') 
Example 16
Project: cyrapidjson   Author: thedrow   File: test_benchmarks.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_double_performance_float_precision(benchmark):
    print("\nArray with 256 doubles:")
    name = 'rapidjson (precise)'
    serialize = rapidjson.dumps
    deserialize = rapidjson.loads

    ser_data, des_data = benchmark(run_client_test,
                                   name, serialize, deserialize,
                                   data=doubles,
                                   iterations=50000,
                                   )
    msg = "%-11s serialize: %0.3f  deserialize: %0.3f  total: %0.3f" % (
        name, ser_data, des_data, ser_data + des_data
    )

    print(msg) 
Example 17
Project: iris-relay   Author: linkedin   File: app.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def on_get(self, req, resp):
        # Username verified in auth middleware
        username = req.context['user']
        access_token = hashlib.sha256(os.urandom(32)).hexdigest()
        encrypted_token = self.fernet.encrypt(access_token.encode('utf8'))
        exp = time.time() + self.access_ttl

        connection = db.connect()
        cursor = connection.cursor()
        try:
            cursor.execute('''INSERT INTO `access_token` (`user_id`, `key`, `expiration`)
                              VALUES ((SELECT `id` FROM `target` WHERE `name` = %s AND `type_id` =
                                      (SELECT `id` FROM `target_type` WHERE `name` = 'user')),
                                      %s,
                                      %s)''',
                           (username, encrypted_token, exp))
            connection.commit()
            key_id = cursor.lastrowid
        finally:
            cursor.close()
            connection.close()

        resp.body = ujson.dumps({'token': access_token, 'key_id': key_id, 'expiry': exp}) 
Example 18
Project: blinker-mpy   Author: blinker-iot   File: Blinker.py    MIT License 6 votes vote down vote up
def print(self, value = None):
        if value:
            self.numberData[BLINKER_CMD_VALUE] = value
        if self._icon:
            self.numberData[BLINKER_CMD_ICON] = self._icon
        if self._color:
            self.numberData[BLINKER_CMD_COLOR] = self._color
        if self._unit:
            self.numberData[BLINKER_CMD_UNIT] = self._unit
        if self._text:
            self.numberData[BLINKER_CMD_TEXT] = self._text

        if len(self.numberData) :
            # data = json.dumps(self.numberData)
            # data = {self.name: self.numberData}
            # Blinker._print(data)
            Blinker.print(self.name, self.numberData)

            self.numberData.clear()

            self._icon = ""
            self._color = ""
            self._unit = ""
            self._text = "" 
Example 19
Project: AutoDL   Author: tanguofu   File: response.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def json(body, status=200, headers=None,
         content_type="application/json", dumps=json_dumps,
         **kwargs):
    """
    Returns response object with body in json format.

    :param body: Response data to be serialized.
    :param status: Response code.
    :param headers: Custom Headers.
    :param kwargs: Remaining arguments that are passed to the json encoder.
    """
    return HTTPResponse(dumps(body, **kwargs), headers=headers,
                        status=status, content_type=content_type) 
Example 20
Project: swaggerit   Author: dutradda   File: test_method_errors.py    MIT License 5 votes vote down vote up
def test_integrity_error_handling_with_duplicated_key(self, post_method, stream, session):
        stream.feed_data(ujson.dumps([{'id': 1}, {'id': 1}]).encode())
        stream.feed_eof()
        request = SwaggerRequest('/model1/', 'post', body=stream, headers={'content-type': 'application/json'})
        resp = await post_method(request, session)

        assert resp.status_code == 400
        assert ujson.loads(resp.body) == {
            'params': [{'id': 1, 'm2_id': None}, {'id': 1, 'm2_id': None}],
            'database message': {
                'message': "Duplicate entry '1' for key 'PRIMARY'",
                'code': 1062
            }
        } 
Example 21
Project: swaggerit   Author: dutradda   File: test_method_errors.py    MIT License 5 votes vote down vote up
def test_model_base_error_handling_with_post_and_with_nested_delete(self, post_method, stream, session):
        body = [{'model2_': {'id': 1, '_operation': 'delete'}}]
        stream.feed_data(ujson.dumps(body).encode())
        stream.feed_eof()
        request = SwaggerRequest('/model1/', 'post', body=stream, headers={'content-type': 'application/json'})
        resp = await post_method(request, session)

        assert resp.status_code == 400
        assert ujson.loads(resp.body) == {
            'instance': body,
            'message': "Can't execute nested 'delete' operation"
        } 
Example 22
Project: swaggerit   Author: dutradda   File: test_method_errors.py    MIT License 5 votes vote down vote up
def test_model_base_error_handling_with_post_and_with_nested_remove(self, post_method, stream, session):
        body = [{'model2_': {'id': 1, '_operation': 'remove'}}]
        stream.feed_data(ujson.dumps(body).encode())
        stream.feed_eof()
        request = SwaggerRequest('/model1/', 'post', body=stream, headers={'content-type': 'application/json'})
        resp = await post_method(request, session)

        assert resp.status_code == 400
        assert ujson.loads(resp.body) == {
            'instance': body,
            'message': "Can't execute nested 'remove' operation"
        } 
Example 23
Project: swaggerit   Author: dutradda   File: test_method_errors.py    MIT License 5 votes vote down vote up
def test_model_base_error_handling_with_post_and_with_nested_update(self, post_method, stream, session):
        body = [{'model2_': {'id': 1, '_operation': 'update'}}]
        stream.feed_data(ujson.dumps(body).encode())
        stream.feed_eof()
        request = SwaggerRequest('/model1/', 'post', body=stream, headers={'content-type': 'application/json'})
        resp = await post_method(request, session)

        assert resp.status_code == 400
        assert ujson.loads(resp.body) == {
            'instance': body,
            'message': "Can't execute nested 'update' operation"
        } 
Example 24
Project: swaggerit   Author: dutradda   File: test_session_integration.py    MIT License 5 votes vote down vote up
def test_if_instance_is_seted_on_redis(self, session, redis):
        session.add(await Model10.new(session, id=1))
        await session.commit()

        assert await redis.hgetall(Model10.__key__) == {b'1': ujson.dumps({'id': 1}).encode()} 
Example 25
Project: swaggerit   Author: dutradda   File: test_session_integration.py    MIT License 5 votes vote down vote up
def test_if_two_instance_are_seted_on_redis(self, session, redis):
        session.add(await Model10.new(session, id=1))
        session.add(await Model10.new(session, id=2))
        await session.commit()

        assert await redis.hgetall(Model10.__key__) == {
            b'1': ujson.dumps({'id': 1}).encode(),
            b'2': ujson.dumps({'id': 2}).encode()
        } 
Example 26
Project: swaggerit   Author: dutradda   File: test_session_integration.py    MIT License 5 votes vote down vote up
def test_if_two_commits_sets_redis_correctly(self, session, redis):
        session.add(await Model10.new(session, id=1))
        await session.commit()

        assert await redis.hgetall(Model10.__key__) == {
            b'1': ujson.dumps({b'id': 1}).encode()
        }

        session.add(await Model10.new(session, id=2))
        await session.commit()

        assert await redis.hgetall(Model10.__key__) == {
            b'1': ujson.dumps({b'id': 1}).encode(),
            b'2': ujson.dumps({b'id': 2}).encode()
        } 
Example 27
Project: swaggerit   Author: dutradda   File: test_session_integration.py    MIT License 5 votes vote down vote up
def test_if_instance_is_deleted_from_redis(self, session, redis):
        inst1 = await Model10.new(session, id=1)
        session.add(inst1)
        await session.commit()

        assert await redis.hgetall(Model10.__key__) == {
            b'1': ujson.dumps({b'id': 1}).encode()
        }

        session.delete(inst1)
        await session.commit()

        assert await redis.hgetall(Model10.__key__) == {} 
Example 28
Project: swaggerit   Author: dutradda   File: test_session_integration.py    MIT License 5 votes vote down vote up
def test_if_istances_are_seted_on_redis_with_two_models_correctly(
            self, session, redis):
        inst1 = await Model10.new(session, id=1)
        inst2 = await Model10.new(session, id=2)
        inst3 = await Model11.new(session, id=1)
        inst4 = await Model11.new(session, id=2)
        session.add_all([inst1, inst2, inst3, inst4])
        await session.commit()

        assert await redis.hgetall(Model10.__key__) == {
            b'1': ujson.dumps({b'id': 1}).encode(),
            b'2': ujson.dumps({b'id': 2}).encode()
        }
        assert await redis.hgetall(Model11.__key__) == {
            b'1': ujson.dumps({b'id': 1}).encode(),
            b'2': ujson.dumps({b'id': 2}).encode()
        }

        session.delete(inst1)
        session.delete(inst2)
        session.delete(inst3)
        session.delete(inst4)
        await session.commit()

        assert await redis.hgetall(Model10.__key__) == {}
        assert await redis.hgetall(Model11.__key__) == {} 
Example 29
Project: swaggerit   Author: dutradda   File: test_sqlalchemy_redis_get_integration.py    MIT License 5 votes vote down vote up
def test_if_query_get_builds_redis_left_ids_correctly_with_one_not_found_on_redis(
            self, session, redis, request):
        met_bkp = redis.hmget
        def fin():
            redis.hmget = met_bkp
        request.addfinalizer(fin)
        redis.hmget = CoroMock()

        session.add(await Model13.new(session, id=1))
        await session.commit()
        redis.hmget.coro.return_value = [None, ujson.dumps({'id': 2})]
        assert await Model13.get(session, [{'id': 1}, {'id': 2}]) == [{'id': 1}, {'id': 2}] 
Example 30
Project: swaggerit   Author: dutradda   File: _base.py    MIT License 5 votes vote down vote up
def _pack_obj(inst, obj):
    return ujson.dumps(obj, escape_forward_slashes=False) 
Example 31
Project: swaggerit   Author: dutradda   File: _swaggerit_meta.py    MIT License 5 votes vote down vote up
def _format_definitions_names(obj, model_name):
    definitions = obj.__swagger_json__.get('definitions', {})
    definitions_keys = list(definitions.keys())
    for def_name in definitions_keys:
        definitions['{}.{}'.format(model_name, def_name)] = definitions.pop(def_name)

    schema = ujson.dumps(obj.__swagger_json__, escape_forward_slashes=False)
    schema = re.sub(r'("\$ref":"#/definitions/)([^/"]+)', r'\1{}.\2'.format(model_name), schema)
    obj.__swagger_json__ = ujson.loads(schema) 
Example 32
Project: swaggerit   Author: dutradda   File: aiohttp_api.py    MIT License 5 votes vote down vote up
def __getitem__(self, k):
        if k == 'SWAGGER_DEF_CONTENT':
            return ujson.dumps(self.swagger_json, escape_forward_slashes=True)
        else:
            return super().__getitem__(k) 
Example 33
Project: aurora   Author: carnby   File: views.py    MIT License 5 votes vote down vote up
def render_json(request, data, dumped=False):
    if dumped:
        code = data
    else:
        code = json.dumps(data)
    return render_to_response('json.html', {'json': code}, context_instance=RequestContext(request), content_type='application/json')


# TODO: this should be a decorator? 
Example 34
Project: aurora   Author: carnby   File: models.py    MIT License 5 votes vote down vote up
def add_request_meta(self, request, ua=None, mobile=False):
        meta = {
            'ip': get_client_ip(request),
            'referer': request.META.get('HTTP_REFERER', ''),
            'user_agent': str(ua) if ua is not None else request.META.get('HTTP_USER_AGENT', ''),
            'mobile': mobile
        }

        self.portrait = Portrait.objects.get(auth_screen_name=request.user.username.lower()) if request.user.is_authenticated() else None
        self.meta = json.dumps(meta) 
Example 35
Project: aurora   Author: carnby   File: importer.py    MIT License 5 votes vote down vote up
def _save_media_urls(cls, media_urls):
        for u in media_urls:
            Media.objects.get_or_create(internal_id=u['id_str'], defaults={
                 'type': u['type'],
                 'media_url': u['media_url'][:255],
                 'display_url': u['display_url'][:255],
                 'expanded_url': u['expanded_url'][:255],
                 'url': u['url'][:255],
                 'sizes': json.dumps(u['sizes'])
            }) 
Example 36
Project: trelliolibs   Author: quikmile   File: helpers.py    MIT License 5 votes vote down vote up
def json_response(data, status=200):
    return Response(content_type='application/json', body=json.dumps(data).encode('utf-8'), status=status) 
Example 37
Project: trelliolibs   Author: quikmile   File: helpers.py    MIT License 5 votes vote down vote up
def paginated_json_response(request: Request, records: list = (), limit=10, prev_offset=None, next_offset=None,
                            last_offset=None, total_records=None, total_pages=None) -> Response:
    if request.headers.get('X-Original-URI'):
        path = request.headers['X-Original-URI'].split('?')[0]
        base_url = '{}://{}/{}/'.format(request.scheme, request.host.strip('/'), path.strip('/'))
    else:
        base_url = request.path

    url = '{}?limit={}'.format(base_url, limit)

    links = []

    first_url = url + '&offset={}'.format(0)
    links.append('<{}>; rel="{}"'.format(first_url, 'first'))

    if next_offset:
        next_url = url + '&offset={}'.format(next_offset)
        links.append('<{}>; rel="{}"'.format(next_url, 'next'))

    if prev_offset:
        prev_url = url + '&offset={}'.format(prev_offset)
        links.append('<{}>; rel="{}"'.format(prev_url, 'prev'))

    if last_offset:
        last_url = url + '&offset={}'.format(last_offset)
        links.append('<{}>; rel="{}"'.format(last_url, 'last'))

    if total_records:
        links.append('<{}>; rel="{}"'.format(total_records, 'total_records'))

    if total_pages:
        links.append('<{}>; rel="{}"'.format(total_pages, 'total_pages'))

    headers = {'Link': ', '.join(links)} if links else {}
    headers['Access-Control-Expose-Headers'] = 'Link'
    return Response(content_type='application/json', body=json.dumps(records).encode('utf-8'), status=200,
                    headers=headers) 
Example 38
Project: trelliolibs   Author: quikmile   File: middlewares.py    MIT License 5 votes vote down vote up
def pre_request(self, service, request, *args, **kwargs):
        if not self.rbac_client:
            raise Exception('Middleware need a rbac client')
        auth_token = request.headers['AUTHORIZATION']
        resource = str(request.rel_url)  # aiohttp request attr
        resource_action = request.method.lower()
        access = await wait_for(self.rbac_client.verify_access(auth_token=auth_token, resource_name=resource,
                                                               resource_action=resource_action,
                                                               resource_type='http'), timeout=None)
        if not access['access']:
            return Response(status=400, content_type='application/json',
                            body=json.dumps(access).encode()) 
Example 39
Project: sanic   Author: huge-success   File: simple_server.py    MIT License 5 votes vote down vote up
def on_get(self, req, resp):
        resp.body = json.dumps({"test": True}) 
Example 40
Project: sanic   Author: huge-success   File: simple_server.py    MIT License 5 votes vote down vote up
def handle(request):
    return web.Response(
        body=json.dumps({"test": True}).encode("utf-8"),
        content_type="application/json",
    ) 
Example 41
Project: sanic   Author: huge-success   File: simple_server.py    MIT License 5 votes vote down vote up
def get(self):
        self.write(ujson.dumps({"test": True})) 
Example 42
Project: sanic   Author: huge-success   File: simple_server.py    MIT License 5 votes vote down vote up
def index():
    return ujson.dumps({"test": True}) 
Example 43
Project: sanic   Author: huge-success   File: simple_server.py    MIT License 5 votes vote down vote up
def index(ctx: HTTPRequestContext):
    return (
        ujson.dumps({"test": True}),
        200,
        {"Content-Type": "application/json"},
    ) 
Example 44
Project: gnocchi   Author: gnocchixyz   File: json.py    Apache License 2.0 5 votes vote down vote up
def dumps(obj):
    return ujson.dumps(to_primitive(obj))


# For convenience 
Example 45
Project: monasca-events-api   Author: openstack   File: test_events_v1.py    Apache License 2.0 5 votes vote down vote up
def test_should_fail_missing_events_in_body(self, bulk_processor):
        events_resource = _init_resource(self)
        events_resource._processor = bulk_processor
        body = {'timestamp': '2012-10-29T13:42:11Z+0200'}
        response = self.simulate_request(
            path=ENDPOINT,
            method='POST',
            headers={
                'Content-Type': 'application/json',
                'X_ROLES': 'monasca-user'
            },
            body=json.dumps(body)
        )
        self.assertEqual(falcon.HTTP_422, response.status) 
Example 46
Project: monasca-events-api   Author: openstack   File: test_events_v1.py    Apache License 2.0 5 votes vote down vote up
def test_should_fail_missing_content_type(self, bulk_processor):
        events_resource = _init_resource(self)
        events_resource._processor = bulk_processor
        body = {'timestamp': '2012-10-29T13:42:11Z+0200'}
        response = self.simulate_request(
            path=ENDPOINT,
            method='POST',
            headers={
                'X_ROLES': 'monasca-user'
            },
            body=json.dumps(body)
        )
        self.assertEqual(falcon.HTTP_400, response.status) 
Example 47
Project: monasca-events-api   Author: openstack   File: test_events_v1.py    Apache License 2.0 5 votes vote down vote up
def test_should_fail_wrong_content_type(self, bulk_processor):
        events_resource = _init_resource(self)
        events_resource._processor = bulk_processor
        body = {'timestamp': '2012-10-29T13:42:11Z+0200'}
        response = self.simulate_request(
            path=ENDPOINT,
            method='POST',
            headers={
                'Content-Type': 'text/plain',
                'X_ROLES': 'monasca-user'
            },
            body=json.dumps(body)
        )
        self.assertEqual(falcon.HTTP_415, response.status) 
Example 48
Project: AppServer   Author: skytoup   File: tests.py    MIT License 5 votes vote down vote up
def put_app_detail(app_id, name, short_chain, detail):
    _, response = app.test_client.put('/apps/{}'.format(app_id),
                                      data=ujson.dumps(dict(name=name, short_chain=short_chain, detail=detail)))
    response_normal_check(response)
    return response 
Example 49
Project: orionx-api-client   Author: itolosa   File: transport.py    MIT License 5 votes vote down vote up
def execute(self, document, variable_values=None, timeout=None):
    query_str = print_ast(document)
    payload = {
      'query': query_str,
      'variables': variable_values or {}
    }

    timestamp = str(time.time())
    data = ujson.dumps(payload)
    signature = str(hmac_sha512(self.secret_key, timestamp, data))

    headers = {
      'Content-Type': 'application/json',
      'X-ORIONX-TIMESTAMP': timestamp,
      'X-ORIONX-APIKEY': self.api_key,
      'X-ORIONX-SIGNATURE': signature
    }

    post_args = {
      'timeout': timeout or self.default_timeout,
      'data': data,
      'headers': headers
    }
    
    request = self.session.post(self.url, **post_args)
    request.raise_for_status()

    result = request.json()
    assert 'errors' in result or 'data' in result, 'Received non-compatible response "{}"'.format(result)
    return ExecutionResult(
      errors=result.get('errors'),
      data=result.get('data')
    ) 
Example 50
Project: micropython-sonoff-switch   Author: kfricke   File: sonoff_switch.py    MIT License 5 votes vote down vote up
def pushbutton_pressed(client, topic):
    global demanded_relay_state
    client.publish(topic, ujson.dumps({'state': demanded_relay_state})) 
Example 51
Project: wallet   Author: clayman74   File: server.py    MIT License 5 votes vote down vote up
def register_service(app: web.Application) -> str:
    config = app["config"]

    service_name = f"{config['app_name']}_{config['app_hostname']}"
    host = config["app_host"]
    port = config["app_port"]

    payload = {
        "ID": service_name,
        "NAME": config["app_name"],
        "Tags": ["master"],
        "Address": host,
        "Port": port,
        "Check": {"HTTP": f"http://{host}:{port}/-/health", "Interval": "10s"},
    }

    url = "http://{host}:{port}/v1/agent/service/register".format(
        host=config["consul_host"], port=config["consul_port"]
    )

    async with ClientSession() as session:
        async with session.put(url, data=ujson.dumps(payload)) as resp:
            assert resp.status == 200

    app.logger.info('Register service "%s"' % service_name)

    return service_name 
Example 52
Project: redis-marshal   Author: mitjafelicijan   File: bottle.py    MIT License 5 votes vote down vote up
def __init__(self, json_dumps=json_dumps):
        self.json_dumps = json_dumps 
Example 53
Project: tomodachi   Author: kalaspuff   File: aws_sns_sqs.py    MIT License 5 votes vote down vote up
def subscribe_topics(cls: Any, topic_arn_list: List, queue_arn: str, queue_url: str, context: Dict, queue_policy: Optional[Dict] = None) -> List:
        if not cls.clients or not cls.clients.get('sns'):
            cls.create_client(cls, 'sns', context)
        client = cls.clients.get('sns')

        if not cls.clients or not cls.clients.get('sqs'):
            cls.create_client(cls, 'sqs', context)
        sqs_client = cls.clients.get('sqs')

        if not queue_policy:
            queue_policy = cls.generate_queue_policy(queue_arn, topic_arn_list, context)

        try:
            # MessageRetentionPeriod (default 4 days, set to context value)
            # VisibilityTimeout (default 30 seconds)
            response = await sqs_client.set_queue_attributes(QueueUrl=queue_url, Attributes={'Policy': ujson.dumps(queue_policy)})
        except botocore.exceptions.ClientError as e:
            error_message = str(e)
            logging.getLogger('transport.aws_sns_sqs').warning('Unable to set queue attributes [sqs] on AWS ({})'.format(error_message))
            raise AWSSNSSQSException(error_message, log_level=context.get('log_level')) from e

        subscription_arn_list = []
        for topic_arn in topic_arn_list:
            try:
                response = await client.subscribe(TopicArn=topic_arn, Protocol='sqs', Endpoint=queue_arn)
            except botocore.exceptions.ClientError as e:
                error_message = str(e)
                logging.getLogger('transport.aws_sns_sqs').warning('Unable to subscribe to topic [sns] on AWS ({})'.format(error_message))
                raise AWSSNSSQSException(error_message, log_level=context.get('log_level')) from e

            subscription_arn = response.get('SubscriptionArn')
            if not subscription_arn:
                error_message = 'Missing Subscription ARN in response'
                logging.getLogger('transport.aws_sns_sqs').warning('Unable to subscribe to topic [sns] on AWS ({})'.format(error_message))
                raise AWSSNSSQSException(error_message, log_level=context.get('log_level'))

            subscription_arn_list.append(subscription_arn)

        return subscription_arn_list 
Example 54
Project: tomodachi   Author: kalaspuff   File: aws_sns_sqs_service_with_credentials_with_custom_protocol.py    MIT License 5 votes vote down vote up
def build_message(cls, service: Any, topic: str, data: Any) -> str:
        message = {
            'protocol': 'custom',
            'data': data
        }
        return ujson.dumps(message) 
Example 55
Project: tomodachi   Author: kalaspuff   File: amqp_service_with_credentials_with_custom_protocol.py    MIT License 5 votes vote down vote up
def build_message(cls, service: Any, topic: str, data: Any) -> str:
        message = {
            'protocol': 'custom',
            'data': data
        }
        return ujson.dumps(message) 
Example 56
Project: decaNLP   Author: salesforce   File: convert_to_logical_forms.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def write_logical_forms(greedy, args):
    data_dir = os.path.join(args.data, 'wikisql', 'data')
    path = os.path.join(data_dir, 'dev.jsonl') if 'valid' in args.evaluate else os.path.join(data_dir, 'test.jsonl')
    table_path = os.path.join(data_dir, 'dev.tables.jsonl') if 'valid' in args.evaluate else os.path.join(data_dir, 'test.tables.jsonl')
    with open(table_path) as tables_file:
        tables = [json.loads(line) for line in tables_file]
        id_to_tables = {x['id']: x for x in tables}

    examples = []
    with open(path) as example_file:
        for line in example_file:
            entry = json.loads(line)
            table = id_to_tables[entry['table_id']]
            sql = entry['sql']
            header = table['header']
            a = repr(Query.from_dict(entry['sql'], table['header']))
            ex = {'sql': sql, 'header': header, 'answer': a, 'table': table}
            examples.append(ex)

    with open(args.output, 'a') as f:
        count = 0
        correct = 0
        text_answers = []
        for idx, (g, ex) in enumerate(zip(greedy, examples)):
            count += 1
            text_answers.append([ex['answer'].lower()])
            try:
                lf = to_lf(g, ex['table'])
                f.write(json.dumps(correct_format(lf)) + '\n')
                gt = ex['sql']
                conds = gt['conds']
                lower_conds = []
                for c in conds:
                    lc = c
                    lc[2] = str(lc[2]).lower()
                    lower_conds.append(lc)
                gt['conds'] = lower_conds
                correct += lf == gt
            except Exception as e:
                f.write(json.dumps(correct_format({})) + '\n') 
Example 57
Project: adaptivemd   Author: markovmodel   File: openmm.py    GNU Lesser General Public License v2.1 5 votes vote down vote up
def _create_output_str(self):
        d = dict()
        for name, opt in self.types.items():
            d[name] = opt.to_dict()

        return '--types="%s"' % ujson.dumps(d).replace('"', "'") 
Example 58
Project: adaptivemd   Author: markovmodel   File: dictify.py    GNU Lesser General Public License v2.1 5 votes vote down vote up
def to_json(self, obj, base_type=''):
        simplified = self.simplify(obj, base_type)
        return ujson.dumps(simplified) 
Example 59
Project: adaptivemd   Author: markovmodel   File: dictify.py    GNU Lesser General Public License v2.1 5 votes vote down vote up
def to_json_object(self, obj):
        if hasattr(obj, 'base_cls') \
                and type(obj) is not type and type(obj) is not abc.ABCMeta:
            simplified = self.simplify_object(obj)
        else:
            simplified = self.simplify(obj)

        return ujson.dumps(simplified) 
Example 60
Project: PyWindowsThingies   Author: forensicmatt   File: trace.py    Apache License 2.0 5 votes vote down vote up
def _event_callback(self, event_record):
        """This function gets called for events.

        :param event_record: (EVENT_RECORD)
        :return: (None)
        """
        if self._callback:
            self._callback(event_record)
        else:
            print(ujson.dumps(event_record.as_dict())) 
Example 61
Project: PyWindowsThingies   Author: forensicmatt   File: print_processes.py    Apache License 2.0 5 votes vote down vote up
def main():
    arguments = get_arguments()
    options = arguments.parse_args()

    for process_entry32 in iterate_processes():
        if options.name:
            if process_entry32.szExeFile.decode("utf-8").lower() == options.name.lower():
                print(ujson.dumps(process_entry32.as_dict()))
        else:
            print(ujson.dumps(process_entry32.as_dict())) 
Example 62
Project: PyWindowsThingies   Author: forensicmatt   File: print_handles.py    Apache License 2.0 5 votes vote down vote up
def main():
    arguments = get_arguments()
    options = arguments.parse_args()

    for handle in iterate_handles(pid=options.pid):
        if options.type is not None:
            try:
                if handle.type_name:
                    if handle.type_name.lower() == options.type.lower():
                        print(ujson.dumps(handle.as_dict()))
            except Exception as error:
                logging.debug(error)
        else:
            print(ujson.dumps(handle.as_dict())) 
Example 63
Project: tributary   Author: timkpaine   File: ws.py    Apache License 2.0 5 votes vote down vote up
def AsyncWebSocket(foo, foo_kwargs=None, url='', json=False, wrap=False, field=None, response=False):
    foo_kwargs = foo_kwargs or {}
    foo = _wrap(foo, foo_kwargs)

    async def _send(foo, url, json=False, wrap=False, field=None, response=False):
        async with websockets.connect(url) as websocket:
            async for data in foo():
                if isinstance(data, StreamNone):
                    continue
                elif not data or isinstance(data, StreamEnd):
                    break

                if wrap:
                    data = [data]
                if json:
                    data = ujson.dumps(data)

                await websocket.send(data)

                if response:
                    msg = await websocket.recv()

                else:
                    msg = '{}'

                if json:
                    msg = json.loads(msg)

                if field:
                    msg = msg[field]

                if wrap:
                    msg = [msg]

                yield msg

    return _wrap(_send, dict(foo=foo, url=url, json=json, wrap=wrap, field=field, response=response), name='WebSocket') 
Example 64
Project: tributary   Author: timkpaine   File: http.py    Apache License 2.0 5 votes vote down vote up
def AsyncHTTP(foo, foo_kwargs=None, url='', json=False, wrap=False, field=None, proxies=None, cookies=None):
    foo_kwargs = foo_kwargs or {}
    foo = _wrap(foo, foo_kwargs)

    async def _send(foo, url, json=False, wrap=False, field=None, proxies=None, cookies=None):
        async for data in foo():
            if wrap:
                data = [data]
            if json:
                data = ujson.dumps(data)

            msg = requests.post(url, data=data, cookies=cookies, proxies=proxies)

            if msg is None:
                break

            if msg.status_code != 200:
                yield msg
                continue

            if json:
                msg = msg.json()

            if field:
                msg = msg[field]

            if wrap:
                msg = [msg]

            yield msg

    return _wrap(_send, dict(foo=foo, url=url, json=json, wrap=wrap, field=field, proxies=proxies, cookies=cookies), name='HTTP') 
Example 65
Project: deoplete-fsharp   Author: callmekohei   File: deoplete-fsharp.py    MIT License 5 votes vote down vote up
def on_init(self, context):

        ### input pattern
        dotHints           = [ r"(\(|<|[a-zA-Z]|\"|\[)*(?<=(\)|>|[a-zA-Z0-9]|\"|\]))\." ]
        oneWordHints       = [ r"^[a-zA-Z]$", "\s*[a-zA-Z]$", "typeof\<[a-zA-Z]$", "(\(\))[a-zA-Z]$", "(\<|\>)[a-zA-Z]$", "(\[|\])[a-zA-Z]$"  ]
        attributeHints     = [ r"\[<[a-zA-Z]*" ]
        self.input_pattern = '|'.join( dotHints + oneWordHints + attributeHints )

        ### initialize of deopletefs
        self.standby  = False
        self.filePath = expand( self.vim.eval( "substitute( expand('%:p') , '\#', '\\#' , 'g' )" ) )
        fsc_path      = expand( re.split('rplugin', __file__)[0] + expand('bin/deopletefs.exe') )

        post_data = {
              "Row"      : -9999 # dummy row
            , "Col"      : 1
            , "Line"     : ''
            , "FilePath" : self.filePath
            , "Source"   : '\n'.join( getlines( self.vim ) )
            , "Init"     : 'true'
        }

        self.util = Util(fsc_path, 20)
        self.util.send(json.dumps(post_data))

        start = time.time()
        self.vim.command("echo '*** deopletefs initializing... ***'")

        if str(self.util.read()) != '':
            self.standby = True
            elapsed_time = time.time() - start
            self.vim.command("echo '*** finish initialize! *** ( time : " + str(round(elapsed_time,6)) + " s )'")
        else:
            elapsed_time = time.time() - start
            self.vim.command("echo '*** Sorry! Please Re-open file! *** ( time : " + str(round(elapsed_time,6)) + " s )'") 
Example 66
Project: deoplete-fsharp   Author: callmekohei   File: deoplete-fsharp.py    MIT License 5 votes vote down vote up
def gather_candidates(self, context):

        try:

            if self.standby == False:
                return [ '=== can not initialize deopletefs ===' ]
            else:
                post_data = {
                      "Row"      : context['position'][1]
                    , "Col"      : context['complete_position'] - 1
                    , "Line"     : context['input']
                    , "FilePath" : self.filePath
                    , "Source"   : '\n'.join( getlines( self.vim ) )
                    , "Init"     : 'false'
                }

                self.util.send(json.dumps(post_data))
                s = (self.util.read())[0]
                s = base64.b64decode(s)
                s = s.decode(encoding='utf-8')
                lst = s.split("\n")

                return [
                    {
                          "word": json_data['word']
                        , "info": '\n'.join( functools.reduce ( lambda a , b : a + b , json_data['info'] ) )
                    }
                    for json_data in [ json.loads(s) for s in lst ]
                ]

        except Exception as e:
            return [ str(e) ] 
Example 67
Project: iris-relay   Author: linkedin   File: app.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def return_slack_message(self, resp, text):
        resp.status = falcon.HTTP_200
        resp.content_type = 'application/json'
        resp.body = ujson.dumps({'text': text,
                                 'replace_original': False}) 
Example 68
Project: cappuccino   Author: FoxDev   File: userdb.py    GNU General Public License v3.0 5 votes vote down vote up
def http_json_dump(data: dict):
    bottle.response.content_type = 'application/json'

    return json.dumps(dict(sorted(data.items(), reverse=True))) 
Example 69
Project: sanic-jsonrpc   Author: mon4ter   File: jsonrpc.py    MIT License 5 votes vote down vote up
def _serialize(self, obj: Any) -> str:
        try:
            return dumps(obj)
        except (TypeError, ValueError) as err:
            # TODO test unserializable response
            logger.error("Failed to serialize object %r: %s", obj, err, exc_info=err)
            return self._serialize(_response(error=INTERNAL_ERROR)) 
Example 70
Project: blinker-mpy   Author: blinker-iot   File: Blinker.py    MIT License 5 votes vote down vote up
def print(self, key, value = None, uint = None):

        if value is None:
            if bProto.isFormat:
                return
            data = str(key)
            BlinkerMpy._print(self, data)
        else:
            key = str(key)
            # if not uint is None:
            #     value = str(value) + str(uint)
            # data = json_encode(key, value)
            # data = {}
            if bProto.isFormat == False:
                bProto.isFormat = True
                bProto.autoFormatFreshTime = millis()
            
            if (millis() - bProto.autoFormatFreshTime) < 100 :
                bProto.autoFormatFreshTime = millis()

            buffer = {}

            if bProto.sendBuf is not '' :
                buffer = ujson.loads(bProto.sendBuf)
            buffer[key] = value
            bProto.sendBuf = ujson.dumps(buffer)
            # # bProto.sendBuf[key] = value

            # # BLINKER_LOG_ALL("key: ", key, ", value: ", bProto.sendBuf[key])
            BLINKER_LOG_ALL("sendBuf: ", bProto.sendBuf) 
Example 71
Project: blinker-mpy   Author: blinker-iot   File: Blinker.py    MIT License 5 votes vote down vote up
def print(self, state=None):

        if state :
            self.buttonData[BLINKER_CMD_SWITCH] = state
        if self._icon:
            self.buttonData[BLINKER_CMD_ICON] = self._icon
        if self.iconClr:
            self.buttonData[BLINKER_CMD_COLOR] = self.iconClr
        if self._content:
            self.buttonData[BLINKER_CMD_CONNECTED] = self._content
        if self._text:
            self.buttonData[BLINKER_CMD_TEXT] = self._text
        if self._text1:
            self.buttonData[BLINKER_CMD_TEXT1] = self._text1
        if self.textClr:
            self.buttonData[BLINKER_CMD_TEXTCOLOR] = self.textClr

        if len(self.buttonData) :
            # data = json.dumps(self.buttonData)
            # data = {self.name: self.buttonData}
            # Blinker._print(data)
            Blinker.print(self.name, self.buttonData)

            self.buttonData.clear()

            self._icon = ""
            self.iconClr = ""
            self._content = ""
            self._text = ""
            self._text1 = ""
            self.textClr = "" 
Example 72
Project: blinker-mpy   Author: blinker-iot   File: Blinker.py    MIT License 5 votes vote down vote up
def print(self, value):
        self.sliderData[BLINKER_CMD_VALUE] = value
        if self.textClr:
            self.sliderData[BLINKER_CMD_COLOR] = self.textClr

        # data = json.dumps(self.sliderData)
        # data = {self.name: self.sliderData}
        # Blinker._print(data)
        Blinker.print(self.name, self.sliderData) 
Example 73
Project: blinker-mpy   Author: blinker-iot   File: Blinker.py    MIT License 5 votes vote down vote up
def print(self, text1, text2=None):
        self.textData[BLINKER_CMD_TEXT] = text1
        if text2:
            self.textData[BLINKER_CMD_TEXT1] = text2

        # data = json.dumps(self.textData)        
        # data = {self.name: self.textData}
        # Blinker._print(data)
        Blinker.print(self.name, self.textData) 
Example 74
Project: blinker-mpy   Author: blinker-iot   File: BlinkerWiFi.py    MIT License 5 votes vote down vote up
def pub(self, msg, state=False):
        if state is False:
            if self.bmqtt.checkCanPrint() is False:
                return
        payload = {'fromDevice': self.bmqtt.deviceName, 'toDevice': self.bmqtt.uuid, 'data': msg , 'deviceType': 'OwnApp'}
        payload = ujson.dumps(payload)
        # if self.bmqtt.isDebugAll() is True:
        BLINKER_LOG_ALL('Publish topic: ', self.bmqtt.pubtopic)
        BLINKER_LOG_ALL('payload: ', payload)
        self.client.publish(self.bmqtt.pubtopic, payload)
        self.bmqtt.printTime = millis() 
Example 75
Project: blinker-mpy   Author: blinker-iot   File: BlinkerWiFi.py    MIT License 5 votes vote down vote up
def aliPrint(self, msg):
        if self.bmqtt.checkAliCanPrint() is False:
            return
        payload = {'fromDevice': self.bmqtt.deviceName, 'toDevice': 'AliGenie_r', 'data': msg , 'deviceType': 'vAssistant'}
        payload = ujson.dumps(payload)
        # if self.bmqtt.isDebugAll() is True:
        BLINKER_LOG_ALL('Publish topic: ', self.bmqtt.pubtopic)
        BLINKER_LOG_ALL('payload: ', payload)
        self.client.publish(self.bmqtt.pubtopic, payload)
        self.bmqtt.aliPrintTime = millis() 
Example 76
Project: blinker-mpy   Author: blinker-iot   File: BlinkerWiFi.py    MIT License 5 votes vote down vote up
def duerPrint(self, msg):
        if self.bmqtt.checkDuerCanPrint() is False:
            return
        payload = {'fromDevice': self.bmqtt.deviceName, 'toDevice': 'DuerOS_r', 'data': msg , 'deviceType': 'vAssistant'}
        payload = ujson.dumps(payload)
        # if self.bmqtt.isDebugAll() is True:
        BLINKER_LOG_ALL('Publish topic: ', self.bmqtt.pubtopic)
        BLINKER_LOG_ALL('payload: ', payload)
        self.client.publish(self.bmqtt.pubtopic, payload) 
Example 77
Project: swaggerit   Author: dutradda   File: method.py    MIT License 4 votes vote down vote up
def __call__(self, req, session):
        denied = await self._authorize(req, session)
        if denied is not None:
            return denied

        response_headers = {'content-type': 'application/json'}

        try:
            body_params = await self._build_body_params(req)
            query_params = self._build_non_body_params(self._query_validator, req.query)
            path_params = self._build_non_body_params(self._path_validator,
                                                               req.path_params)
            headers_params = self._build_non_body_params(self._headers_validator, dict(req.headers))

        except (ValidationError, SchemaError) as error:
            return self._valdation_error_to_response(error, response_headers)

        req = SwaggerRequest(
            req.path,
            req.method,
            scheme=req.scheme,
            host=req.host,
            path_params=path_params,
            query=query_params,
            headers=headers_params,
            body=body_params,
            body_schema=self._body_validator.schema if self._body_validator else None,
            context=req.context
        )

        try:
            if session is None:
                resp = await self._operation(req)
            else:
                resp = await self._operation(req, session)

        except (ValidationError, SchemaError) as error:
            return self._valdation_error_to_response(error, response_headers)

        except Exception as error:
            body = ujson.dumps({'message': 'Something unexpected happened'})
            self._logger.exception('Unexpected')
            return SwaggerResponse(500, body=body, headers=response_headers)

        else:
            if resp.headers.get('content-type') is None:
                resp.headers.update(response_headers)
            return resp 
Example 78
Project: aurora   Author: carnby   File: views.py    MIT License 4 votes vote down vote up
def view_portrait(request, screen_name):
    print(screen_name)
    portrait = get_object_or_404(Portrait, auth_screen_name=screen_name.lower(), active=True)

    if not portrait.public_access_enabled:
        if not request.user.is_authenticated() or request.user.username.lower() != screen_name.lower():
            return render_to_response('portraits/protected.html', {
                'portrait_screen_name': screen_name,
                'portrait_pk': portrait.pk,
                'profile_data': json.dumps(portrait.user_data)
            }, context_instance=RequestContext(request))

    if not portrait.portrait_content:
        return render_to_response('portraits/wait.html', {
            'portrait_screen_name': screen_name,
            'portrait_pk': portrait.pk,
            'profile_data': json.dumps(portrait.user_data),
            'demo_portrait': portrait.demo_portrait
        }, context_instance=RequestContext(request))

    record_interactions = False
    show_recommendations = False

    if request.user.is_authenticated():
        record_interactions = True
        auth_portrait = Portrait.objects.get(auth_screen_name=request.user.username.lower(), active=True)

        if auth_portrait == portrait:
            show_recommendations = True
            portrait.last_access = timezone.now()
            portrait.save()

        if not 'experimental_group' in request.session or not 'portraits' in request.session['experimental_group']:
            print('preparing session')
            prepare_session(request, '{0}_{1}'.format(auth_portrait.condition_ui, auth_portrait.condition_rec), 'portraits')
            print(request.session)

    return render_to_response('portraits/portrait.html', {
        'portrait_screen_name': screen_name,
        'portrait_current_pk': portrait.pk,
        'condition_ui': portrait.condition_ui,
        'condition_rec': portrait.condition_rec,
        'last_update': portrait.last_update_date.isoformat(),
        'demo_portrait': portrait.demo_portrait,
        'show_recommendations': show_recommendations,
        'record_interactions': record_interactions,
        'current_app': 'portraits',
        'client_datetime_var': 'client_datetime'
    }, context_instance=RequestContext(request)) 
Example 79
Project: aurora   Author: carnby   File: views.py    MIT License 4 votes vote down vote up
def record_event(request):
    check_referer(request)

    ua = agentparse(request.META.get('HTTP_USER_AGENT', ''))
    print(ua)

    if ua.is_bot:
        raise PermissionDenied()

    session = request.session

    if 'experimental_group' not in session:
        raise PermissionDenied()

    if not 'source_app' in request.POST:
        print('no source app in POST', request.POST)
        raise Http404

    source_app = request.POST.get('source_app', None)
    if not source_app or not source_app in ('aurora', 'portraits'):
        print('invalid app', source_app)
        raise Http404

    if not 'user_events' in request.POST:
        print('no user events in POST', request.POST)
        raise Http404

    print('POST', request.POST)

    user_events_str = str(request.POST['user_events'])

    try:
        user_events = json.loads(user_events_str)
    except ValueError:
        raise Http404

    print(session.session_key)
    print(session['experimental_group'])

    for event in user_events:
        print(source_app, 'event', event)
        try:
            interaction = InteractionEvent(session=session.session_key,
                             experimental_group=session['experimental_group'][source_app],
                             source_app=source_app,
                             key=event['name'],
                             data=json.dumps(event),
                             reported_datetime=event['client_datetime'])
            interaction.add_request_meta(request, ua=ua, mobile=(ua.is_mobile or ua.is_tablet or bool(request.GET.get('mobile_version', False))))
            interaction.save()
        except KeyError:
            continue

    return render_json(request, {'json': True}) 
Example 80
Project: orionx-api-client   Author: itolosa   File: transport.py    MIT License 4 votes vote down vote up
def _batch_query(self):
    while self.query_batcher_active:
      query_payloads = []
      futures = []
      payload, future = self.query_batcher_queue.get()

      if not self.query_batcher_active:
        break
      query_payloads.append(payload)
      futures.append(future)
      # wait 10 ms
      time.sleep(0.01)
      while not self.query_batcher_queue.empty():
        if not self.query_batcher_active:
          break
        payload, future = self.query_batcher_queue.get()
        query_payloads.append(payload)
        futures.append(future)

      new_futures = []
      new_query_payloads = []
      for payload, future in zip(query_payloads, futures):

        if future.set_running_or_notify_cancel():
          new_futures.append(future)
          new_query_payloads.append(payload)

      try:
        data = ujson.dumps(new_query_payloads)
        timestamp = str(time.time())
        signature = str(hmac_sha512(self.secret_key, timestamp, data))

        headers = {
          'Content-Type': 'application/json',
          'X-ORIONX-TIMESTAMP': timestamp,
          'X-ORIONX-APIKEY': self.api_key,
          'X-ORIONX-SIGNATURE': signature
        }

        post_args = {
          'timeout': self.timeout,
          'data': data,
          'headers': headers
        }

        request = self.session.post(self.url, **post_args)
        request.raise_for_status()
        results = request.json()
        for result, future in zip(results, new_futures):
          try:
            assert 'errors' in result or 'data' in result, \
                'Received non-compatible response "{}"'.format(result)
            future.set_result(result)
          except Exception as exc:
            future.set_exception(exc)
      except Exception as exc:
        for future in new_futures:
          future.set_exception(exc)