当前位置: 首页>>代码示例>>Python>>正文


Python rapidjson.loads方法代码示例

本文整理汇总了Python中rapidjson.loads方法的典型用法代码示例。如果您正苦于以下问题:Python rapidjson.loads方法的具体用法?Python rapidjson.loads怎么用?Python rapidjson.loads使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在rapidjson的用法示例。


在下文中一共展示了rapidjson.loads方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: users

# 需要导入模块: import rapidjson [as 别名]
# 或者: from rapidjson import loads [as 别名]
def users(self, request: web.Request):
        cached = await RedisDB.instance().get("apiuserscache")
        if cached is not None:
            return web.json_response(
                data=json.loads(cached),
                dumps=json.dumps
            )
        # Get all of not cached
        users = await User.all().prefetch_related('account')
        resp = []
        for user in users:
            resp.append(
                {
                    'user_id': user.id,
                    'user_last_known_name': user.name,
                    'address': user.account.address,
                    'created_ts_utc': self.format_js_iso(user.created_at)
                }
            )
        await RedisDB.instance().set("apiuserscache", json.dumps(resp), expires=1800)
        return web.json_response(
            data=resp,
            dumps=json.dumps
        ) 
开发者ID:bbedward,项目名称:graham_discord_bot,代码行数:26,代码来源:server.py

示例2: validate_id

# 需要导入模块: import rapidjson [as 别名]
# 或者: from rapidjson import loads [as 别名]
def validate_id(tx_body):
        """Validate the transaction ID of a transaction

            Args:
                tx_body (dict): The Transaction to be transformed.
        """
        # NOTE: Remove reference to avoid side effects
        # tx_body = deepcopy(tx_body)
        tx_body = rapidjson.loads(rapidjson.dumps(tx_body))

        try:
            proposed_tx_id = tx_body['id']
        except KeyError:
            raise InvalidHash('No transaction id found!')

        tx_body['id'] = None

        tx_body_serialized = Transaction._to_str(tx_body)
        valid_tx_id = Transaction._to_hash(tx_body_serialized)

        if proposed_tx_id != valid_tx_id:
            err_msg = ("The transaction's id '{}' isn't equal to "
                       "the hash of its body, i.e. it's not valid.")
            raise InvalidHash(err_msg.format(proposed_tx_id)) 
开发者ID:bigchaindb,项目名称:bigchaindb,代码行数:26,代码来源:transaction.py

示例3: store_bulk_transactions

# 需要导入模块: import rapidjson [as 别名]
# 或者: from rapidjson import loads [as 别名]
def store_bulk_transactions(self, transactions):
        txns = []
        assets = []
        txn_metadatas = []
        for t in transactions:
            transaction = t.tx_dict if t.tx_dict else rapidjson.loads(rapidjson.dumps(t.to_dict()))
            if transaction['operation'] == t.CREATE:
                asset = transaction.pop('asset')
                asset['id'] = transaction['id']
                assets.append(asset)

            metadata = transaction.pop('metadata')
            txn_metadatas.append({'id': transaction['id'],
                                  'metadata': metadata})
            txns.append(transaction)

        backend.query.store_metadatas(self.connection, txn_metadatas)
        if assets:
            backend.query.store_assets(self.connection, assets)
        return backend.query.store_transactions(self.connection, txns) 
开发者ID:bigchaindb,项目名称:bigchaindb,代码行数:22,代码来源:lib.py

示例4: _init_json

# 需要导入模块: import rapidjson [as 别名]
# 或者: from rapidjson import loads [as 别名]
def _init_json(self):
        # rapidjson is well maintained library with acceptable performance, good choice
        if self.options['json_lib'] == 'rapidjson':
            import rapidjson

            self.json_encode = lambda x: rapidjson.dumps(x, number_mode=rapidjson.NM_NATIVE)
            self.json_decode = lambda x: rapidjson.loads(x, number_mode=rapidjson.NM_NATIVE)

        # ujson provides best performance in our tests, but it is abandoned by maintainers
        elif self.options['json_lib'] == 'ujson':
            import ujson

            self.json_encode = ujson.dumps
            self.json_decode = ujson.loads

        # json from Python stdlib, very safe choice, but slow
        elif self.options['json_lib'] == 'json':
            import json

            self.json_encode = json.dumps
            self.json_decode = json.loads

        else:
            raise ValueError(f"Unsupported json library [{self.options['json_lib']}]") 
开发者ID:badoo,项目名称:pyexasol,代码行数:26,代码来源:connection.py

示例5: loads

# 需要导入模块: import rapidjson [as 别名]
# 或者: from rapidjson import loads [as 别名]
def loads(string: str, *args, **kwargs) -> Dict:
    kwargs = add_settings_to_kwargs(kwargs)
    return rapidjson.loads(string, *args, **kwargs) 
开发者ID:alexferl,项目名称:falcon-boilerplate,代码行数:5,代码来源:json.py

示例6: callback

# 需要导入模块: import rapidjson [as 别名]
# 或者: from rapidjson import loads [as 别名]
def callback(self, request: web.Request):
        """Route for handling HTTP callback"""
        request_json = await request.json()
        hash = request_json['hash']
        self.logger.debug(f"callback received {hash}")
        # cache
        if not await RedisDB.instance().exists(f"callback:{hash}"):
            await RedisDB.instance().set(f"callback:{hash}", "val", expires=300)
        else:
            return web.HTTPOk()
        # De-serialize block
        request_json['block'] = json.loads(request_json['block'])
        # only consider sends
        if 'is_send' in request_json and (request_json['is_send'] or request_json['is_send'] == 'true'):
            if 'amount' in request_json:
                # only consider self.min_amount or larger
                converted_amount = Env.raw_to_amount(int(request_json['amount']))
                if converted_amount >= self.min_amount:
                    # Figure out of this is one of our users
                    link = request_json['block']['link_as_account']
                    account = await Account.filter(address=link).prefetch_related('user').first()
                    if account is None:
                        return web.HTTPOk()
                    # See if this is an internal TX
                    transaction = await Transaction.filter(block_hash=hash).prefetch_related('receiving_user').first()
                    if transaction is not None and transaction.receiving_user is not None:
                        return web.HTTPOk()
                    self.logger.debug(f'Deposit received: {request_json["amount"]} for {account.user.id}')
                    amount_string = f"{Env.raw_to_amount(int(request_json['amount']))} {Env.currency_symbol()}"
                    discord_user = await self.bot.fetch_user(account.user.id)
                    if discord_user is not None:
                        await Messages.send_success_dm(discord_user, f"Your deposit of **{amount_string}** has been received. It will be in your available balance shortly!", header="Deposit Success", footer=f"I only notify you of deposits that are {self.min_amount} {Env.currency_symbol()} or greater.")
        return web.HTTPOk() 
开发者ID:bbedward,项目名称:graham_discord_bot,代码行数:35,代码来源:server.py

示例7: auto_rain_eligible

# 需要导入模块: import rapidjson [as 别名]
# 或者: from rapidjson import loads [as 别名]
def auto_rain_eligible(msg: discord.Message):
        # Ignore if user doesnt have rain role
        has_rain_role = False
        rain_roles = config.Config.instance().get_rain_roles()
        if len(rain_roles) > 0:
            for role in msg.author.roles:
                if role.id in rain_roles:
                    has_rain_role = True
                    break
            if not has_rain_role:
                return

        # Get user OBJ from redis if it exists, else create one
        user_key = f"activity:{msg.guild.id}:{msg.author.id}"
        active_stats = await RedisDB.instance().get(user_key)
        if active_stats is None:
            # Create stats and save
            active_stats = {
                'user_id': msg.author.id,
                'last_msg': datetime.datetime.utcnow().strftime('%m/%d/%Y %H:%M:%S'),
                'msg_count': Constants.RAIN_MSG_REQUIREMENT * 2
            }
            await RedisDB.instance().set(user_key, json.dumps(active_stats), expires=1800)
            return
        else:
            active_stats = json.loads(active_stats)
            if active_stats['msg_count'] < Constants.RAIN_MSG_REQUIREMENT * 2:
                active_stats['msg_count'] = Constants.RAIN_MSG_REQUIREMENT * 2
            active_stats['last_msg'] = datetime.datetime.utcnow().strftime('%m/%d/%Y %H:%M:%S')
            await RedisDB.instance().set(user_key, json.dumps(active_stats), expires=1800) 
开发者ID:bbedward,项目名称:graham_discord_bot,代码行数:32,代码来源:rain.py

示例8: get_active

# 需要导入模块: import rapidjson [as 别名]
# 或者: from rapidjson import loads [as 别名]
def get_active(ctx: Context, excluding: int = 0) -> List[User]:
        """Return a list of active users"""
        msg = ctx.message
        redis = await RedisDB.instance().get_redis()

        # Get all activity stats from DB
        users_list = []
        async for key in redis.iscan(match=f"*activity:{msg.guild.id}*"):
            u = await redis.get(key)
            if u is not None:
                users_list.append(json.loads(u))

        if len(users_list) == 0:
            return []

        # Get IDs that meet requirements
        users_filtered = []
        for u in users_list:
            if u['user_id'] == excluding:
                continue
            elif u['msg_count'] >= Constants.RAIN_MSG_REQUIREMENT:
                users_filtered.append(u['user_id'])

        if len(users_filtered) < 1:
            return []

        # Get only users in our database
        return await User.filter(id__in=users_filtered, frozen=False, tip_banned=False).prefetch_related('account').all() 
开发者ID:bbedward,项目名称:graham_discord_bot,代码行数:30,代码来源:rain.py

示例9: get_replay

# 需要导入模块: import rapidjson [as 别名]
# 或者: from rapidjson import loads [as 别名]
def get_replay(self, id):
        """Description: Send the action to the server for playing out  
        Arguments:  
        * id: The ID of the match to be replayed"""
        self._send(intent=constants.NetworkCommands.replay.value, replay_id=id)
        try:
            status, replay = rapidjson.loads(
                str(gzip.decompress(self.ws_.recv()), "utf-8"))
        except ValueError:
            raise Exception(constants.Exceptions.replay_notfound.value)
        if status == constants.NetworkCommands.status_ok.value:
            return replay
        else:
            raise Exception(constants.Exceptions.replay_notfound.value) 
开发者ID:MultiAgentLearning,项目名称:playground,代码行数:16,代码来源:network.py

示例10: _recieve

# 需要导入模块: import rapidjson [as 别名]
# 或者: from rapidjson import loads [as 别名]
def _recieve(self):
        self.lock.acquire()
        try:
            message_recieved = self.ws_.recv()
        except:
            if not self.ws_.connected:
                raise Exception(constants.Exceptions.net_server_closed.value)
            else:
                raise Exception(constants.Exceptions.net_invalid_response.value)
        finally:
            self.lock.release()
        try:
            return rapidjson.loads(message_recieved)
        except:
            raise Exception(constants.Exceptions.net_invalid_response.value) 
开发者ID:MultiAgentLearning,项目名称:playground,代码行数:17,代码来源:network.py

示例11: ws_handler

# 需要导入模块: import rapidjson [as 别名]
# 或者: from rapidjson import loads [as 别名]
def ws_handler(websocket, pth=None):  # pylint: disable=unused-argument
    """Handle the messages recieved by WebSocket (pth is not required but still\
returned by the 'websockets' library)"""
    try:
        async for message in websocket:
            try:
                await message_parse(rapidjson.loads(message), websocket)
            except:
                pass
    except websockets.exceptions.ConnectionClosed:
        pass 
开发者ID:MultiAgentLearning,项目名称:playground,代码行数:13,代码来源:network.py

示例12: get_query_params

# 需要导入模块: import rapidjson [as 别名]
# 或者: from rapidjson import loads [as 别名]
def get_query_params(self, query_id: str) -> dict:
        query_params_str = self.redis_client.get(query_id)
        if query_params_str is None:
            raise UnkownQueryIdError(f"Unknown query_id: '{query_id}'")
        return rapidjson.loads(query_params_str) 
开发者ID:Flowminder,项目名称:FlowKit,代码行数:7,代码来源:query_info_lookup.py

示例13: deserialize

# 需要导入模块: import rapidjson [as 别名]
# 或者: from rapidjson import loads [as 别名]
def deserialize(data):
    """Deserialize a JSON formatted string into a dict.

        Args:
            data (str): JSON formatted string.

        Returns:
            dict: dict resulting from the serialization of a JSON formatted
            string.
    """
    return rapidjson.loads(data) 
开发者ID:bigchaindb,项目名称:bigchaindb,代码行数:13,代码来源:utils.py

示例14: json_loads

# 需要导入模块: import rapidjson [as 别名]
# 或者: from rapidjson import loads [as 别名]
def json_loads(x):
    return json.loads(x) 
开发者ID:qsniyg,项目名称:rssit,代码行数:4,代码来源:util.py

示例15: dolartoday_bolivar

# 需要导入模块: import rapidjson [as 别名]
# 或者: from rapidjson import loads [as 别名]
def dolartoday_bolivar():
    response = json.loads(requests.get(url=dolartoday_price).text)
    if "USD" not in response:
        print("Invalid response " + str(response))
        return
    bolivarprice = response['USD']['localbitcoin_ref']
    if bolivarprice is None:
        print("Couldn't find localbitcoin_ref price")
        return
    print(rdata.hset("prices", "dolartoday:usd-ves", bolivarprice),
          "DolarToday USD-VES", bolivarprice) 
开发者ID:appditto,项目名称:natrium-wallet-server,代码行数:13,代码来源:vesprice.py


注:本文中的rapidjson.loads方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。