本文整理匯總了Python中db.DB.get方法的典型用法代碼示例。如果您正苦於以下問題:Python DB.get方法的具體用法?Python DB.get怎麽用?Python DB.get使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類db.DB
的用法示例。
在下文中一共展示了DB.get方法的11個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import get [as 別名]
def __init__(self):
# create a new window
self.window = Gtk.Window(gtk.WINDOW_TOPLEVEL)
self.grid = Gtk.Grid()
self.grid.set_column_homogeneous(True)
self.grid.set_row_homogeneous(True)
self.add(self.grid)
self.ab_liststore = Gtk.ListStore(str, str)
# When the window is given the "delete_event" signal (this is given
# by the window manager, usually by the "close" option, or on the
# titlebar), we ask it to call the delete_event () function
# as defined above. The data passed to the callback
# function is NULL and is ignored in the callback function.
self.window.connect("delete_event", self.delete_event)
# Here we connect the "destroy" event to a signal handler.
# This event occurs when we call Gtk_widget_destroy() on the window,
# or if we return FALSE in the "delete_event" callback.
self.window.connect("destroy", self.destroy)
# Sets the border width of the window.
self.window.set_border_width(10)
# Creates a new button with the label "Hello World".
self.button = Gtk.Button("Hello World")
# When the button receives the "clicked" signal, it will call the
# function hello() passing it None as its argument. The hello()
# function is defined above.
# This will cause the window to be destroyed by calling
# Gtk_widget_destroy(window) when "clicked". Again, the destroy
# signal could come from here, or the window manager.
# self.button.connect_object("clicked", Gtk.Widget.destroy, self.window)
# This packs the button into the window (a GTK container).
self.window.add(self.button)
# The final step is to display this newly created widget.
self.button.show()
# and the window
returned_values = DB().getlogin()
uid = returned_values.get('uid')
username = returned_values.get('uname')
self.button.connect("clicked", self.printAB, returned_values)
if uid:
#ArbeitsberichteWindow.uid = uid
#ArbeitsberichteWindow.username = username
self.window.show()
#Gtk.main()
else:
sys.exit(0)
示例2: main
# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import get [as 別名]
def main():
'constructor for your class instances'
parse_options()
# Run the application.
returned_values = DB().getlogin()
uid = returned_values.get('uid')
username = returned_values.get('uname')
if uid:
ArbeitsberichteWindow.uid = uid
ArbeitsberichteWindow.username = username
window = ArbeitsberichteWindow.ArbeitsberichteWindow()
window.show()
Gtk.main()
else:
sys.exit(0)
示例3: ChainManager
# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import get [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'))
#.........這裏部分代碼省略.........
示例4: ChainManager
# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import get [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)
#.........這裏部分代碼省略.........
示例5: searchActiveCount
# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import get [as 別名]
def searchActiveCount():
db = DB(devConfig)
sql = "select count(*) from active where (auth_password is null or auth_password = '') and deleted = 0"
result = db.get(sql)
return result[0]
示例6: Trie
# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import get [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))
#.........這裏部分代碼省略.........
示例7: do_GET
# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import get [as 別名]
def do_GET(self):
request = re.findall("([^/]+)", unquote(self.path))
#print self.path
#print request
if not request or request[0] == "index":
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.end_headers()
index = open("%s/data/index.html" % self.server.abspath, "r")
self.copyfile(index, self.wfile)
index.close()
elif request[0] == "data":
try:
path = "%s/%s" % (self.server.abspath, re.search("([^?#]+).*", unquote(self.path)).groups()[0])
if not os.path.exists(os.path.realpath(path)):
self.send_response(404)
else:
mime = mimetypes.types_map[re.search("(\.\w+)$", path, re.I).groups()[0]]
self.send_response(200)
self.send_header("Content-Type", mime)
self.end_headers()
resource = open(path, "r")
self.copyfile(resource, self.wfile)
resource.close()
except:
self.send_response(500)
self.end_headers()
elif request[0] == "mounts":
try:
db = DB("%s/stats.sqlite" % self.server.abspath)
data = StringIO()
data.write(json.dumps(db.mounts()))
data.seek(0)
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.copyfile(data, self.wfile)
except:
self.send_response(500)
self.end_headers()
elif request[0] == "mount":
try:
db = DB("%s/stats.sqlite" % self.server.abspath)
data = StringIO()
data.write(json.dumps(db.get(request[1], (len(request) > 2 and int(request[2]) or 0), (len(request) > 3 and int(request[3]) or 0))))
data.seek(0)
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.copyfile(data, self.wfile)
except Exception as e:
print e
self.end_headers()
self.send_response(500)
示例8: searchActiveRecordCount
# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import get [as 別名]
def searchActiveRecordCount():
db = DB(devConfig)
sql = "select count(*) from active_record where deleted = 0 and (uid = 0 or uid is null)"
result = db.get(sql)
return result[0]
示例9: ChainManager
# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import get [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
示例10: Bot
# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import get [as 別名]
class Bot(object):
def __init__(self, host, port, chan, nick, ident, realname):
self.host = host
self.port = port
self.chan = chan
self.nick = nick
self.ident = ident
self.realname = realname
self.recv_buffer = ''
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.db = DB()
def connect(self):
self.socket.connect((self.host, self.port))
self.send('NICK {}\r\n'.format(self.nick))
self.send('USER {} {} bla :{}\r\n'.format(self.ident, self.host, self.realname))
time.sleep(3)
self.send('JOIN {}\r\n'.format(self.chan))
def send(self, msg):
self.socket.send(bytes('{}\r\n'.format(msg), 'UTF-8'))
print('send: ' + msg)
def recv(self):
self.recv_buffer = self.socket.recv(1024).decode('UTF-8')
temp = str.split(self.recv_buffer, '\n')
for line in temp:
try:
line = str.rstrip(line)
line = str.split(line)
if (line[0] == 'PING'):
self.send('PONG {}'.format(line[1]))
except:
pass
print('recv: ' + self.recv_buffer)
def translate(self, m):
# Parse IRC messages. Stolen from muirc (https://github.com/Gawen/muirc)
IRC_RE = re.compile(r"(:(?P<nick>[^ [email protected]]+)(\!(?P<user>[^ @]+))?(\@(?P<host>[^ ]+))? )?(?P<command>[^ ]+) (?P<params1>([^:]*))(?P<params2>(:.*)?)")
if isinstance(m, str):
# str -> msg
m = IRC_RE.match(m.strip())
if not m:
return None
m = m.groupdict()
m["params"] = m.pop("params1").split()
if m["params2"]: m["params"] += [m["params2"][1:]]
m.pop("params2")
return m
else:
# msg -> str
def gen():
if m.get("nick", None):
yield ":" + m["nick"]
if m.get("user", None): yield "!" + m["user"]
if m.get("host", None): yield "@" + m["host"]
yield " "
yield m["command"]
if m.get("params", None):
for param in m["params"][:-1]: yield " " + param
yield " "
if " " in m["params"][-1]: yield ":"
yield m["params"][-1]
yield ''
return "".join(gen())
def message(self, chan, msg):
self.send('PRIVMSG {} :{}'.format(chan, msg))
def log(self, msg):
with open('log.txt', 'a') as f:
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
f.write(now+str(msg)+'\n')
def main(self):
msg = self.translate(self.recv_buffer)
self.log(msg)
if msg['command'] == 'PRIVMSG':
time.sleep(0.5)
sender = msg['nick']
channel = msg['params'][0].lower()
message = msg['params'][1].lower()
if self.nick.lower() in message:
#.........這裏部分代碼省略.........
示例11: Song
# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import get [as 別名]
class Song(object):
def __init__(self, song_id=None):
self.db = DB()
self.current_song_id = song_id # current song
def get_song_by_id(self, song_id):
sql = 'select * from songs where id = {0}'.format(song_id)
song = self.db.get(sql)
if song:
self.unset_playing()
self.current_song_id = song.id
self.set_playing(song.id)
return song
def _get_current_song(self):
if self.current_song_id:
song = self.db.get('select * from songs where id = {0}'.format(self.current_song_id))
else:
sql = 'select * from songs where is_playing = 1 limit 1'
song = self.db.get(sql)
if song:
self.current_song_id = song.id
else:
sql = 'select * from songs limit 1'
song = self.db.get(sql)
if song:
self.unset_playing()
self.current_song_id = song.id
self.set_playing(song.id)
return song
def get_meta_data(self):
if self.current_song_id:
song = self.db.get('select * from songs where id = {0}'.format(self.current_song_id))
return song
return {}
def _get_song(self, next=True):
if not self.current_song_id:
song = self.db.get('select * from songs limit 1')
else:
sql = 'select * from songs where id > {0} limit 1'.format(self.current_song_id)
if not next: # previous
sql = 'select * from songs where id < {0} order by id desc limit 1'.format(self.current_song_id)
song = self.db.get(sql)
if not song:
sql = 'select * from songs limit 1'
if not next:
sql = 'select * from songs order by id desc limit 1'
song = self.db.get(sql)
if song:
self.current_song_id = song.id
self.unset_playing()
self.set_playing(song.id)
return song
@property
def current_song(self):
song = self._get_current_song()
return song
@property
def next_song(self):
song = self._get_song(next=True)
return song
@property
def previous_song(self):
song = self._get_song(next=False)
return song
def set_playing(self, song_id):
sql = 'update songs set is_playing = 1 where id = {0}'.format(song_id)
self.db.execute(sql)
def unset_playing(self):
sql = 'update songs set is_playing = 0 where is_playing = 1'
self.db.execute(sql)
def get_all_songs(self):
sql = 'select * from songs'
return self.db.query(sql)