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


Python DataBase.find方法代码示例

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


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

示例1: Engine

# 需要导入模块: from database import DataBase [as 别名]
# 或者: from database.DataBase import find [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 } )
#.........这里部分代码省略.........
开发者ID:Azarn,项目名称:pyMediaMonitor,代码行数:103,代码来源:main.py

示例2: TestDB

# 需要导入模块: from database import DataBase [as 别名]
# 或者: from database.DataBase import find [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' )
#.........这里部分代码省略.........
开发者ID:Azarn,项目名称:pyMediaMonitor,代码行数:103,代码来源:tests.py

示例3: Action

# 需要导入模块: from database import DataBase [as 别名]
# 或者: from database.DataBase import find [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
#.........这里部分代码省略.........
开发者ID:acknowledge,项目名称:NFCGolfBallDispenser-UI,代码行数:103,代码来源:action.py


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