當前位置: 首頁>>代碼示例>>Python>>正文


Python DB.put方法代碼示例

本文整理匯總了Python中db.DB.put方法的典型用法代碼示例。如果您正苦於以下問題:Python DB.put方法的具體用法?Python DB.put怎麽用?Python DB.put使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在db.DB的用法示例。


在下文中一共展示了DB.put方法的6個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: fmpi

# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import put [as 別名]
    def fmpi(self):
        '''循環檢測'''
        while True:
            query = DB.getall(self)
            try:
                one = query[0]
            except:
                one = None
            os.system("clear")
            if one is not None:
                logging.info('>>>>%s' % one[1])
                if one[1].startswith('http://'):  # 直接播放url對應的音樂
                    if one[1].endswith('.mp3'):
                        self.play(one[1], config.freq, config.rate)
                    else:
                        links = get_all_mp3(one[1])
                        for i in links:
                            DB.put(self, i)
                else:
                    url = getlink(one[1].encode('utf-8'))
                    self.play(url, config.freq, config.rate)
                DB.updateone(self, one[0])
            else:
#                rand_music = self.get_random_music()
                douban_music = self.get_douban_music()
                DB.put(self, douban_music)
            time.sleep(1)  # 降低CPU占用率
開發者ID:Cration,項目名稱:fmpi,代碼行數:29,代碼來源:fmpi.py

示例2: ChainManager

# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import put [as 別名]
class ChainManager(StoppableLoopThread):

    """
    Manages the chain and requests to it.
    """

    def __init__(self):
        super(ChainManager, self).__init__()
        # initialized after configure
        self.miner = None
        self.blockchain = None
        self._children_index = None

    def configure(self, config, genesis=None):
        self.config = config
        logger.info('Opening chain @ %s', utils.get_db_path())
        self.blockchain = DB(utils.get_db_path())
        self._children_index = indexdb.Index('ci')
        if genesis:
            self._initialize_blockchain(genesis)
        logger.debug('Chain @ #%d %s', self.head.number, self.head.hex_hash())
        self.log_chain()
        self.new_miner()

    @property
    def head(self):
        if 'HEAD' not in self.blockchain:
            self._initialize_blockchain()
        ptr = self.blockchain.get('HEAD')
        return blocks.get_block(ptr)

    def _update_head(self, block):
        bh = block.hash
        self.blockchain.put('HEAD', block.hash)
        self.blockchain.commit()
        self.new_miner()  # reset mining

    def get(self, blockhash):
        assert isinstance(blockhash, str)
        assert len(blockhash) == 32
        return blocks.get_block(blockhash)

    def has_block(self, blockhash):
        assert isinstance(blockhash, str)
        assert len(blockhash) == 32
        return blockhash in self.blockchain

    def __contains__(self, blockhash):
        return self.has_block(blockhash)

    def _store_block(self, block):
        self.blockchain.put(block.hash, block.serialize())
        self.blockchain.commit()

    def _initialize_blockchain(self, genesis=None):
        logger.info('Initializing new chain @ %s', utils.get_db_path())
        if not genesis:
            genesis = blocks.genesis()
        self._store_block(genesis)
        self._update_head(genesis)

    def synchronize_newer_blockchain(self):
        logger.info('sync newer request for head %r', self.head)
        signals.remote_chain_requested.send(
            sender=None, parents=[self.head.hash], count=NUM_BLOCKS_PER_REQUEST)

    def synchronize_older_blockchain(self, block_number):
        # block_number: for block we search the parent for
        # seek 1st possible branching block
        logger.info('sync older request for parent of block #%r', block_number)
        blk = self.head
        while blk.number > block_number:
            blk = blk.get_parent()

        # collect blocks
        requested = []
        while len(requested) < NUM_BLOCKS_PER_REQUEST and blk.has_parent():
            blk = blk.get_parent()
            requested.append(blk)
        logger.debug('requesting %d blocks', len(requested))
        # newest first, GetChain, will try to answer w/ older ones if the
        # the newest is not in the canonical chain
        # expected answer is the first here known block in the canonical chain
        signals.remote_chain_requested.send(sender=None,
                                            parents=[b.hash for b in requested], count=NUM_BLOCKS_PER_REQUEST)

    def loop_body(self):
        ts = time.time()
        pct_cpu = self.config.getint('misc', 'mining')
        if pct_cpu > 0:
            self.mine()
            delay = (time.time() - ts) * (100. / pct_cpu - 1)
            time.sleep(min(delay, 1.))
        else:
            time.sleep(.01)

    def new_miner(self):
        "new miner is initialized if HEAD is updated"
        uncles = self.get_uncles(self.head)
        miner = Miner(self.head, uncles, self.config.get('wallet', 'coinbase'))
#.........這裏部分代碼省略.........
開發者ID:VIAAC,項目名稱:pyethereum,代碼行數:103,代碼來源:chainmanager.py

示例3: add_music

# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import put [as 別名]
 def add_music(self,music_name):
     if self.check_name_exist(music_name) is False:
         DB.put(self,music_name)
         return None
     else:
         return '''<head><meta charset="UTF-8"></head>
開發者ID:cloudaice,項目名稱:fmpi,代碼行數:8,代碼來源:web_server.py

示例4: ChainManager

# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import put [as 別名]
class ChainManager(StoppableLoopThread):

    """
    Manages the chain and requests to it.
    """

    def __init__(self):
        super(ChainManager, self).__init__()
        # initialized after configure
        self.miner = None
        self.blockchain = None

    def configure(self, config):
        self.config = config
        logger.info('Opening chain @ %s', utils.get_db_path())
        self.blockchain = DB(utils.get_db_path())
        logger.debug('Chain @ #%d %s', self.head.number, self.head.hex_hash())
        self.log_chain()
        self.new_miner()

    @property
    def head(self):
        if 'HEAD' not in self.blockchain:
            self._initialize_blockchain()
        ptr = self.blockchain.get('HEAD')
        return blocks.get_block(ptr)

    def _update_head(self, block):
        bh = block.hash
        self.blockchain.put('HEAD', block.hash)
        self.blockchain.commit()
        self.new_miner()  # reset mining

    def get(self, blockhash):
        return blocks.get_block(blockhash)

    def has_block(self, blockhash):
        return blockhash in self.blockchain

    def __contains__(self, blockhash):
        return self.has_block(blockhash)

    def _store_block(self, block):
        self.blockchain.put(block.hash, block.serialize())
        self.blockchain.commit()
        assert block == blocks.get_block(block.hash)

    def _initialize_blockchain(self):
        logger.info('Initializing new chain @ %s', utils.get_db_path())
        genesis = blocks.genesis()
        self._store_block(genesis)
        self._update_head(genesis)
        self.blockchain.commit()

    def synchronize_blockchain(self):
        logger.info('synchronize requested for head %r', self.head)

        signals.remote_chain_requested.send(
            sender=None, parents=[self.head.hash], count=30)

    def loop_body(self):
        ts = time.time()
        pct_cpu = self.config.getint('misc', 'mining')
        if pct_cpu > 0:
            self.mine()
            delay = (time.time() - ts) * (100. / pct_cpu - 1)
            time.sleep(min(delay, 1.))
        else:
            time.sleep(.1)

    def new_miner(self):
        "new miner is initialized if HEAD is updated"
        miner = Miner(self.head, self.config.get('wallet', 'coinbase'))
        if self.miner:
            for tx in self.miner.get_transactions():
                miner.add_transaction(tx)
        self.miner = miner

    def mine(self):
        with self.lock:
            block = self.miner.mine()
            if block:
                # create new block
                self.add_block(block)
                logger.debug("broadcasting new %r" % block)
                signals.send_local_blocks.send(
                    sender=None, blocks=[block])  # FIXME DE/ENCODE

    def receive_chain(self, blocks):
        old_head = self.head
        # assuming chain order w/ newest block first
        for block in blocks:
            if block.hash in self:
                logger.debug('Known %r', block)
            else:
                if block.has_parent():
                    # add block & set HEAD if it's longest chain
                    success = self.add_block(block)
                    if success:
                        logger.debug('Added %r', block)
#.........這裏部分代碼省略.........
開發者ID:mrmayfield,項目名稱:pyethereum,代碼行數:103,代碼來源:chainmanager.py

示例5: Trie

# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import put [as 別名]
class Trie(object):

    def __init__(self, dbfile, root=BLANK_NODE):
        '''
        :param dbfile: key value database
        :root: blank or trie node in form of [key, value] or [v0,v1..v15,v]
        '''
        self.root = root
        dbfile = os.path.abspath(dbfile)
        self.db = DB(dbfile)

    def clear(self):
        ''' clear all tree data
        '''
        # FIXME: remove saved (hash, value) from database
        self.root = BLANK_NODE

    def _inspect_node(self, node):
        ''' get node type and content

        :param node: node or hash
        :return: (NODE_TYPE_*, content), content is the decoded node,
        unless a key-value node, which will result a (key, value)
        with key is nibbles without the terminator
        '''
        content = self._rlp_decode(node)

        if not content:
            return (NODE_TYPE_BLANK, BLANK_NODE)

        if len(content) == 2:
            nibbles = unpack_to_nibbles(content[0])
            has_terminator = (nibbles and nibbles[-1] == NIBBLE_TERMINATOR)
            content = (without_terminator(nibbles), content[1])
            return (NODE_TYPE_LEAF_KEY_VALUE, content) if has_terminator\
                else (NODE_TYPE_INNER_KEY_VALUE, content)

        if len(content) == 17:
            return (NODE_TYPE_DIVERGE_WITH_VALUE, content) if content[-1]\
                else (NODE_TYPE_DIVERGE_WITHOUT_VALUE, content)

    def _get(self, node, is_node, key):
        """ get value inside a node

        :param node: node or hash
        :param is_node: node is a node or a value
        :param key: nibble list without terminator
        :return: None if does not exist, otherwise value or hash
        is_node denote whether the node is a node or a value
        """
        if not is_node:
            if not key:
                return node, False
            return None, False

        node_type, content = self._inspect_node(node)

        if node_type == NODE_TYPE_BLANK:
            return None, False

        if is_diverge_type(node_type):
            # already reach the expected node
            if not key:
                return content[-1] if content[-1] else None, False
            return self._get(content[key[0]], True, key[1:])

        # key value node
        (curr_key, curr_val) = content
        if node_type == NODE_TYPE_LEAF_KEY_VALUE:
            if key == curr_key:
                return curr_val, True
            # not found
            else:
                return None, True

        if node_type == NODE_TYPE_INNER_KEY_VALUE:
            # traverse child nodes
            if starts_with(key, curr_key):
                return self._get(curr_val, True, key[len(curr_key):])
            else:
                return None, True

    def _rlp_encode(self, node):
        rlpnode = rlp.encode(node)
        if len(rlpnode) < 32:
            return node

        hashkey = sha3(rlpnode)
        self.db.put(hashkey, rlpnode)
        return hashkey

    def _rlp_decode(self, node):
        if not isinstance(node, (str, unicode)):
            return node
        elif len(node) == 0:
            return node
        elif len(node) < 32:
            return node
        else:
            return rlp.decode(self.db.get(node))
#.........這裏部分代碼省略.........
開發者ID:ebuchman,項目名稱:daoist_protocol,代碼行數:103,代碼來源:trie.py

示例6: ChainManager

# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import put [as 別名]
class ChainManager(StoppableLoopThread):

    """
    Manages the chain and requests to it.
    """

    def __init__(self):
        super(ChainManager, self).__init__()
        self.transactions = set()
        self.blockchain = DB(utils.get_db_path())
        self.head = None
        # FIXME: intialize blockchain with genesis block

    def _initialize_blockchain(self):
        genesis = blocks.genesis()

    # Returns True if block is latest
    def add_block(self, block):

        blockhash = block.hash()
        if blockhash == GENESIS_H:
            parent_score = 0
        else:
            try:
                parent = rlp.decode(self.blockchain.get(block.prevhash))
            except:
                raise Exception("Parent of block not found")
            parent_score = utils.big_endian_to_int(parent[1])
        total_score = utils.int_to_big_endian(block.difficulty + parent_score)
        self.blockchain.put(
            blockhash, rlp.encode([block.serialize(), total_score]))
        try:
            head = self.blockchain.get('head')
            head_data = rlp.decode(self.blockchain.get(head))
            head_score = utils.big_endian_to_int(head_data[1])
        except:
            head_score = 0
        if total_score > head_score:
            self.head = blockhash
            self.blockchain.put('head', blockhash)
            return True
        return False

    def configure(self, config):
        self.config = config

    def synchronize_blockchain(self):
        # FIXME: execute once, when connected to required num peers
        if self.head:
            return
        signals.remote_chain_requested.send(
            sender=self, parents=[GENESIS_H], count=30)

    def loop_body(self):
        self.mine()
        time.sleep(10)
        self.synchronize_blockchain()

    def mine(self):
        "in the meanwhile mine a bit, not efficient though"
        pass

    def recv_blocks(self, block_lst):
        """
        block_lst is rlp decoded data
        """

        block_lst.reverse()  # oldest block is sent first in list

        # FIXME validate received chain, compare with local chain
        for data in block_lst:
            logger.debug("processing block: %r" % rlp_hash_hex(data))
            block = Block.deserialize(rlp.encode(data))
            h = rlp_hash(data)
            try:
                self.blockchain.get(h)
            except KeyError:
                self.add_block(block)
                new_blocks_H.add(h)

 #       for h in new_blocks_H:
 #           logger.debug("recv_blocks: ask for child block %r" %
 #                        h.encode('hex'))
 #           signals.remote_chain_requested.send(
 #               sender=self, parents=[h], count=1)
    def add_transactions(self, transactions):
        logger.debug("add transactions %r" % transactions)
        for tx in transactions:
            self.transactions.add(tx)

    def get_transactions(self):
        logger.debug("get transactions")
        return self.transactions
開發者ID:zancas,項目名稱:pyethereum,代碼行數:95,代碼來源:chainmanager.py


注:本文中的db.DB.put方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。