本文整理汇总了Python中database.DataBase.update方法的典型用法代码示例。如果您正苦于以下问题:Python DataBase.update方法的具体用法?Python DataBase.update怎么用?Python DataBase.update使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类database.DataBase
的用法示例。
在下文中一共展示了DataBase.update方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __update_database
# 需要导入模块: from database import DataBase [as 别名]
# 或者: from database.DataBase import update [as 别名]
def __update_database(self, star, word):
"updates database when a word is starred/unstarred"
from database import DataBase
import pickle
database = DataBase()
table = (len(word.query) > 1 and word.query[1] != " ") and word.query[:2] or word.query[:1]
data = star.state == True and pickle.dumps(word) or None
database.update(table.lower(), (word.query.lower(), data, "bengali"))
database.close()
示例2: _toggle_row_cb
# 需要导入模块: from database import DataBase [as 别名]
# 或者: from database.DataBase import update [as 别名]
def _toggle_row_cb(self, widget, path):
'''Toggle button row'''
model = self.tasks_list.get_model()
row_iter = model.get_iter(path)
#row is a gtk.TreeModelRow()
row = model[row_iter]
row[4] = not row[4]
#task, completed, id for the moment category and
#priority are excluded
data = (row[4], row[0])
db = DataBase(self.path)
db.update(data)
db.close()
self.get_tasks()
示例3: TestDB
# 需要导入模块: from database import DataBase [as 别名]
# 或者: from database.DataBase import update [as 别名]
class TestDB( unittest.TestCase ):
dbData = { 'dir': 'TEST_DIR',
'tags': { 'test_tag_1': 1,
'test tag 2': 2,
'test!/|[email protected] tag 3': 1,
'тест тэг 4': 4 },
'media': [ { 'file': '1.jpg', 'dir': 'test_content', 'size': 587370, 'created': 1389078966, 'tags': { 'тест тэг 4', 'test!/|[email protected] tag 3' },
'url': 'http://2.bp.blogspot.com/-722WR2hJZNk/T4HplxWF9WI/AAAAAAAAles/nzwyIIR-If0/s1600/162985+-+artist+john_joseco+cake+celestia.jpg',
'hash': None, 'google': 'princess celestia cake' },
{ 'file': '2.jpg', 'dir': 'test content 2', 'size': 622645, 'created': 1389078965, 'tags': { 'тест тэг 4', 'test_tag_1', 'test tag 2' },
'url': 'http://poniez.net/images/2012/07/16/3Bz2F.jpg',
'hash': None, 'google': 'мир пони' },
{ 'file': '3.jpg', 'dir': 'тест контент 3', 'size': 5784745, 'created': 1389078965, 'tags': { 'тест тэг 4', 'test tag 2' },
'url': 'https://static1.e621.net/TEST_DIR/sample/01/76/017691130342c69beb81ce71e2399df0.jpg',
'hash': None, 'google': 'luna celestia' },
{ 'file': '4.jpg', 'dir': 'unknown dir', 'size': 5784745, 'created': 1389078955, 'tags': { 'тест тэг 4' },
'url': 'https://pp.vk.me/c409823/v409823018/8ad0/9_S0XT7uEcQ.jpg',
'hash': None, 'google': None }
]
}
def setUp( self ):
self.db = DataBase()
self.db.db = deepcopy( self.dbData )
def tearDown( self ):
del self.db
def test_load_db( self ):
with open( 'TEST_DIR/test_db', 'wb' ) as f:
pickle.dump( self.dbData, f )
self.db.load_db( 'xxxxxxxxxxxxxxxxxxxxxxx' )
self.assertEqual( self.db.db, self.db.EMPTY_DB )
self.db.load_db( 'TEST_DIR/test_db' )
self.assertEqual( self.db.db, self.dbData )
os.unlink( 'TEST_DIR/test_db' )
def test_find_file( self ):
self.assertEqual( self.db.find( file = '3.jpg' ), [ self.dbData['media'][2] ] )
def test_find_dir( self ):
self.assertEqual( self.db.find( dir = 'test_content' ), [ self.dbData['media'][0] ] )
def test_find_size( self ):
self.assertEqual( self.db.find( size = 0 ), [] )
def test_find_created( self ):
self.assertEqual( self.db.find( created = 1389078966 ), [ self.dbData['media'][0] ] )
def test_find_tags( self ):
self.assertEqual( self.db.find( tags = {'test tag 2'} ), [ self.dbData['media'][1], self.dbData['media'][2] ] )
def test_find_url_regex( self ):
self.assertEqual( self.db.find( url = r'\.net/', flags = {'re': True} ), [ self.dbData['media'][1], self.dbData['media'][2] ] )
def test_find_hash( self ):
self.assertEqual( self.db.find( hash = None ), [ self.dbData['media'][0], self.dbData['media'][1], self.dbData['media'][2], self.dbData['media'][3] ] )
def test_find_google( self ):
self.assertEqual( self.db.find( google = None ), [ self.dbData['media'][3] ] )
def test_find_both_hash_url( self ):
self.assertEqual( self.db.find( hash = None, url = 'net', flags = {'re': True} ), [ self.dbData['media'][1], self.dbData['media'][2] ] )
def test_add( self ):
self.db.add( file = 'test', hash = 'xxx' )
found = self.db.find( file = 'test' )
self.assertEqual( len( found ), 1 )
self.assertEqual( self.db.db['tags']['Unsorted'], 1 )
self.assertEqual( found[0]['hash'], 'xxx' )
self.assertIn( found[0], self.db.db['media'] )
self.assertEqual( found[0]['created'], None )
def test_add_with_tag( self ):
self.db.add( file = 'test_tag', tags = {'unique_test_tag'} )
self.assertIn( 'unique_test_tag', self.db.find( file = 'test_tag' )[0]['tags'] )
self.assertIn( 'unique_test_tag', self.db.db['tags'] )
self.assertEqual( self.db.db['tags']['unique_test_tag'], 1 )
def test_add_full( self ):
elem = self.dbData['media'][3]
elem['file'] = 'test.png'
self.db.add( **elem )
self.assertEqual( self.db.find( file = 'test.png' ), [elem] )
self.assertEqual( self.db.db['tags']['тест тэг 4'], self.dbData['tags']['тест тэг 4'] + 1 )
def test_remove( self ):
self.assertIn( self.dbData['media'][0], self.db.db['media'] )
self.db.remove( file = '1.jpg' )
self.assertNotIn( self.dbData['media'][0], self.db.db['media'] )
self.assertEqual( self.db.db['tags']['тест тэг 4'], self.dbData['tags']['тест тэг 4'] - 1 )
self.assertNotIn( 'test!/|[email protected] tag 3', self.db.db['tags'].keys() )
def test_update_file( self ):
self.db.add( file = 'filename', hash = 'xxx' )
self.db.update( {'file': 'filename'}, {'file': 'new_filename', 'hash': 'new'} )
elem = self.db.find( file = 'new_filename', hash = 'new' )
self.assertEqual( len( self.db.find( hash = 'xxx' ) ), 0 )
self.assertEqual( len( elem ), 1 )
self.assertEqual( elem[0]['hash'], 'new' )
#.........这里部分代码省略.........
示例4: Engine
# 需要导入模块: from database import DataBase [as 别名]
# 或者: from database.DataBase import update [as 别名]
class Engine( watchdog.events.FileSystemEventHandler ):
#DEFAULT_CFG = [r'D:\disk\Projects\pyMediaMonitor\WATCH_DIR']
DEFAULT_CFG = [r'D:\disk\Pictures\ponies']
DEFAULT_CFG_NAME = 'cfg'
def __init__( self, outFunc = None ):
watchdog.events.FileSystemEventHandler.__init__( self )
if not outFunc:
outFunc = lambda x: True
self.outFunc = outFunc
self.ignoreFiles = []
self.db = DataBase()
self.queue = queue.Queue()
self.worker = threading.Thread( target = self.worker )
def setNotifyOnChange( self, path, isRecursive = False ):
self.observer = watchdog.observers.Observer()
self.observer.schedule( self, path = path, recursive = isRecursive )
self.observer.start()
def loadCfg( self, cfgName = None ):
if not cfgName:
cfgName = self.DEFAULT_CFG_NAME
try:
with open( cfgName, 'rb' ) as f:
self.cfg = pickle.load( f )
except FileNotFoundError:
self.cfg = self.DEFAULT_CFG
def writeCfg( self, cfgName = None ):
if not cfgName:
cfgName = self.DEFAULT_CFG_NAME
with open( cfgName, 'wb' ) as f:
pickle.dump( self.cfg, f )
def run( self ):
self.loadCfg()
self.db.load_db()
self.setNotifyOnChange( self.cfg[0], True )
self.worker.start()
try:
while True:
inp = input()
if inp == 'd':
print( self.db.db )
elif inp == 'u':
self.updateAllInPath( self.cfg[0], self.cfg[0] )
time.sleep( 0.5 )
except KeyboardInterrupt:
self.queue.put( 'quit' )
self.worker.join()
def worker( self ):
while True:
o = self.queue.get( True )
if isinstance( o, str ) and o == 'quit':
break
if len( o ) == 3:
task, query, func = o
elif len( o ) == 2:
task, query = o
func = lambda x: None
else:
raise TypeError( 'Неверный формат задания! Его длина равна {0}.'.format( len( o ) ) )
if func == None:
func = lambda x: None
if task == 'query':
func( self.db.find( **query ) )
def addTask( self, task, resultFunc, **data ):
self.queue.put( ( task, resultFunc, data ) )
def updateAllInPath( self, path, root ):
path = os.path.join( path, '*' )
for f1 in glob.iglob( path ):
if os.path.isdir( f1 ):
path2 = os.path.join( f1, '*' )
for f2 in glob.iglob( path2 ):
if os.path.isdir( f2 ):
self.processEvent( self.prepareEvent( f2, root, Event.ACTION.BROKEN_STRUCTURE ) )
else:
self.processEvent( self.prepareEvent( f2, root, Event.ACTION.NEW ) )
else:
self.processEvent( self.prepareEvent( f1, root, Event.ACTION.NEW ) )
def processEvent( self, event ):
if event.action != Event.ACTION.NOT_PROCESSING and self.outFunc( event ):
if event.action == Event.ACTION.NEW:
self.db.add( file = event.fileName, dir = event.directory, hash = event.info ) # TODO: Делать запрос в гугл ( и другие операции )
elif event.action == Event.ACTION.MISSING:
self.db.remove( file = event.fileName, dir = event.directory )
elif event.action == Event.ACTION.DUPLICATE:
self.ignoreFiles.append( event.path )
os.unlink( event.path )
elif event.action == Event.ACTION.UPDATED:
self.db.update( { 'file': event.fileName, 'dir': event.directory },
{ 'hash': event.info } )
#.........这里部分代码省略.........
示例5: __save
# 需要导入模块: from database import DataBase [as 别名]
# 或者: from database.DataBase import update [as 别名]
def __save(self, unused):
'saves the contact details'
def show_message(msg_type, msg_format, text, button =
gtk.BUTTONS_CLOSE):
'''
shows warning/error messages if
anything goes wrong in contact info
'''
def set_flag(unused_button):
'''
sets the flag to overwrite same
contact name with newer details
'''
self.__over_write = True
return False
self.__over_write = False
message = gtk.MessageDialog(type = msg_type, message_format =
msg_format, buttons = button)
message.format_secondary_markup(text)
message.set_icon_from_file(ICON_PATH + '/contact.png')
if button == gtk.BUTTONS_YES_NO:
message.get_child().get_children()[-1].get_children()[0].\
connect('clicked', set_flag)
message.run()
message.destroy()
if not self.entry_list[0].get_text():
show_message(gtk.MESSAGE_ERROR, 'ERROR', '<span font_desc=\
"belgrano 12">Name can not be empty</span>')
return False
elif not self.entry_list[1].get_text():
show_message(gtk.MESSAGE_ERROR, 'ERROR', '<span font_desc="primitiv\
e 12"><span foreground="#3EA9DC"><b>' + self.entry_list[0].get_text() + \
'</b></span> must have a default number</span>')
return False
else:
faulty = []
for entry in range(1, len(self.entry_list)):
if len(self.entry_list[entry].get_text()) < 10:
faulty.append(entry)
if faulty:
text = '<span font_desc="belgrano 12">The following contact(s)\
has(have) less than 10 digits :\n'
for index in faulty:
if index == 1:
text += '<b>default</b>\n'
else:
text += '#<b>' + str(index) + '</b>\n'
text += '</span>'
show_message(gtk.MESSAGE_ERROR, 'ERROR', text)
return False
values = [self.entry_list[1].get_text(), self.entry_list[0].get_text()]
for entry in self.entry_list[2:]:
values.append(entry.get_text())
values = tuple(values)
from database import DataBase
database = DataBase()
if database.row_count('contacts', self.entry_list[1].get_text()):
show_message(gtk.MESSAGE_WARNING, 'WARNING', '<span font_desc="belgrano 12">Number <span foreground="#0000FF"><b>' + \
self.entry_list[1].get_text() + '</b></span> is already in use for <span foreground="#FF0000"><b>%s</b></span>\n\nOverwrite the \
details for <span foreground="#077E11"><b>%s</b></span> ?</span>' % (database.select('contacts', self.entry_list[1].get_text())[0][0],
self.entry_list[0].get_text()), gtk.BUTTONS_YES_NO)
if self.__over_write:
database.update('contacts', values)
database.close()
self.destroy()
else:
database.update('contacts', values)
database.close()
self.destroy()
示例6: Action
# 需要导入模块: from database import DataBase [as 别名]
# 或者: from database.DataBase import update [as 别名]
class Action(QObject):
"""! @brief
Binding between the card reader and the database.
@author CASAS Jacky
@date 22.06.14
@version 1.0
"""
## Signal used to display the action status on the UI
status = Signal(str)
## Signal used to display the last transactions on the UI
transactionsLoaded = Signal(list)
def __init__(self, pifacecontrol):
"""! @brief Initialize the instance and get the two collections of the database.
@param self the Action instance
"""
QObject.__init__(self)
## contains a link to the database collection *user*
self.users = DataBase().user
## contains a link to the database collection *transaction*
self.transactions = DataBase().transaction
self.piFace = pifacecontrol
self.piFace.activateButtonListener()
def transaction(self, deviceId, amount):
"""! @brief Method to make a transaction (withdraw an amount from an account).
@param self the Action instance
@param deviceId identifier of the device (smartcard or smartphone)
@param amount amount to withdraw
"""
canWithdraw = False
user = self.users.find_one({"devices.uid": deviceId})
for device in user['devices']:
if device['uid'] == deviceId:
if device['status'] == STA_DEVICE_ACTIVE:
if amount > 0:
if user['balance'] >= amount:
canWithdraw = True
else:
self.status.emit('Please recharge your account, you don\'t have enough money in it.')
else:
self.status.emit('The amount must be greater than 0.')
elif device['status'] == STA_DEVICE_LOST:
self.status.emit('Impossible transaction : Lost device.')
elif device['status'] == STA_DEVICE_STOLEN:
self.status.emit('Impossible transaction : Stolen device.')
elif device['status'] == STA_DEVICE_DELETED:
self.status.emit('Impossible transaction : Deleted device.')
else:
self.status.emit('Impossible transaction : Device status unknown.')
if canWithdraw:
# create transaction
userId = user['uid']
dispenserId = DISPENSER_ID
transactionDate = datetime.now()
transaction = {"userId":userId, "deviceId":deviceId, "dispenserId":dispenserId, "transactionType":WITHDRAWAL, "amount":amount, "transactionDate":transactionDate}
self.transactions.insert(transaction)
# debit credit in account
query = {"uid": user['uid'] }
update = {"$inc": { "balance": -amount}}
self.users.update(query, update)
self.status.emit('You withdraw ' + `amount` + ' CHF. You have now ' + `user['balance'] - amount` + ' CHF on your account.')
self.piFace.actionValidated()
else:
self.piFace.actionDenied()
break
def recharge(self, deviceId, amount):
"""! @brief Method to make a recharge (put an amount in an account).
@param self the Action instance
@param deviceId identifier of the device (smartcard or smartphone)
@param amount amount to recharge
"""
canRecharge = False
user = self.users.find_one({"devices.uid": deviceId})
for device in user['devices']:
if device['uid'] == deviceId:
if device['status'] == STA_DEVICE_ACTIVE:
if amount > 0:
canRecharge = True
else:
self.status.emit('The amount must be greater than 0.')
elif device['status'] == STA_DEVICE_LOST:
self.status.emit('Impossible recharge : Lost device.')
elif device['status'] == STA_DEVICE_STOLEN:
self.status.emit('Impossible recharge : Stolen device.')
elif device['status'] == STA_DEVICE_DELETED:
self.status.emit('Impossible recharge : Deleted device.')
else:
self.status.emit('Impossible recharge : Device status unknown.')
if canRecharge:
# create transaction
userId = user['uid']
dispenserId = DISPENSER_ID
#.........这里部分代码省略.........