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


Python TinyDB.get方法代码示例

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


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

示例1: __init__

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import get [as 别名]
class DB:
    def __init__(self,db_path):
        self.db = TinyDB(db_path)

    def add(self, data):
        # Only add it if you can't find it
        Track = Query()
        if not self.db.get(Track.display_id == data['display_id']):
            return self.db.insert(data)

    def searchById(self, video_id):
        Track = Query()
        return self.db.get(Track.display_id == video_id)

    def search(self, text):
        pattern = re.compile(text,re.IGNORECASE)
        def test(txt):
            return pattern.search(txt)

        Track = Query()
        q = Track.title.test(test) | Track.description.test(test)
        return self.db.search(q)

    def all(self):
        return self.db.all()
开发者ID:captn3m0,项目名称:playtube,代码行数:27,代码来源:db.py

示例2: is_vip

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import get [as 别名]
def is_vip(author):
	vip_db = TinyDB("dbs/vips.json")
	try:
		vip_db.get(where("email") == author)
		return True
	except:
		return False
开发者ID:fhebert-perkins,项目名称:helpdesk,代码行数:9,代码来源:maildaemon.py

示例3: TinyDBStore

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import get [as 别名]
class TinyDBStore(object):
    def __init__(self):
        self.drafts_db = TinyDB('event_drafts.json')
        self.events_db = TinyDB('events.json')

    # Drafts
    def contains_draft(self, user_id):
        return self.drafts_db.contains(Query().user_id == user_id)

    def new_draft(self, user_id):
        if self.contains_draft(user_id):
            self.drafts_db.remove(Query().user_id == user_id)

        self.drafts_db.insert({
            'user_id': user_id,
            'current_field': 0,
            'event': {}
        })

    def update_draft(self, user_id, event, current_field):
        self.drafts_db.update({
            'user_id': user_id,
            'current_field': current_field,
            'event': event
        }, Query().user_id == user_id)

    def get_draft(self, user_id):
        return self.drafts_db.get(Query().user_id == user_id)

    def remove_draft(self, user_id):
        self.drafts_db.remove(Query().user_id == user_id)

    # Events
    def insert_event(self, event):
        event_id = self.events_db.insert(event)
        event['id'] = event_id
        return event

    def update_event(self, event):
        self.events_db.update(event, eids=[event.eid])

    def remove_event(self, event):
        self.events_db.remove(eids=[event['id']])

    def get_events(self, user_id, name=None):
        if name:
            return self.events_db.search((Query().user_id == user_id) & (Query().name.test(lambda v: name in v)))
        return self.events_db.search(Query().user_id == user_id)

    def get_event(self, event_id):
        return self.events_db.get(eid=int(event_id))
开发者ID:lukaville,项目名称:create-event-bot,代码行数:53,代码来源:store.py

示例4: test_json_readwrite

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import get [as 别名]
def test_json_readwrite(tmpdir):
    """
    Regression test for issue #1
    """
    path = str(tmpdir.join('test.db'))

    # Create TinyDB instance
    db = TinyDB(path, storage=JSONStorage)

    item = {'name': 'A very long entry'}
    item2 = {'name': 'A short one'}

    get = lambda s: db.get(where('name') == s)

    db.insert(item)
    assert get('A very long entry') == item

    db.remove(where('name') == 'A very long entry')
    assert get('A very long entry') is None

    db.insert(item2)
    assert get('A short one') == item2

    db.remove(where('name') == 'A short one')
    assert get('A short one') is None
开发者ID:lordjabez,项目名称:tinydb,代码行数:27,代码来源:test_storages.py

示例5: test_process

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import get [as 别名]
def test_process(tmpdir, capsys, side_effect, success):
    db_fn = tmpdir.join('database.json')
    log_dir = tmpdir.mkdir('log')
    db = TinyDB(db_fn.strpath)
    process_me = '/my/path/A12345'
    accession_number = op.basename(process_me)
    paths2process = {process_me: 42}
    with patch('subprocess.Popen') as mocked_popen:
        stdout = b"INFO: PROCESSING STARTS: {'just': 'a test'}"
        mocked_popen_instance = mocked_popen.return_value
        mocked_popen_instance.side_effect = side_effect
        mocked_popen_instance.communicate.return_value = (stdout, )
        # set return value for wait
        mocked_popen_instance.wait.return_value = 1 - success
        # mock also communicate to get the supposed stdout
        process(paths2process, db, wait=-30, logdir=log_dir.strpath)
        out, err = capsys.readouterr()
        log_fn = log_dir.join(accession_number + '.log')

        mocked_popen.assert_called_once()
        assert log_fn.check()
        assert log_fn.read() == stdout.decode('utf-8')
        assert db_fn.check()
        # dictionary should be empty
        assert not paths2process
        assert out == 'Time to process {0}\n'.format(process_me)

        # check what we have in the database
        Path = Query()
        query = db.get(Path.input_path == process_me)
        assert len(db) == 1
        assert query
        assert query['success'] == success
        assert query['accession_number'] == op.basename(process_me)
        assert query['just'] == 'a test'
开发者ID:cni-md,项目名称:heudiconv,代码行数:37,代码来源:test_monitor.py

示例6: runs2json

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import get [as 别名]
def runs2json():
    run_ids = literal_eval(request.form['run_ids'])
    db = TinyDB(recipyGui.config.get('tinydb'))
    runs = [db.get(eid=run_id) for run_id in run_ids]
    db.close()

    response = make_response(dumps(runs, indent=2, sort_keys=True))
    response.headers['content-type'] = 'application/json'
    response.headers['Content-Disposition'] = 'attachment; filename=runs.json'
    return response
开发者ID:pablo-esteban,项目名称:recipy,代码行数:12,代码来源:views.py

示例7: run_details

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import get [as 别名]
def run_details():
        form = SearchForm()
        annotateRunForm = AnnotateRunForm()
        query = request.args.get('query', '')
        run_id = int(request.args.get('id'))

        db = TinyDB(recipyGui.config.get('tinydb'))
        r = db.get(eid=run_id)

        db.close()

        return render_template('details.html', query=query, form=form,
                               annotateRunForm=annotateRunForm, run=r)
开发者ID:rddaz2013,项目名称:recipy,代码行数:15,代码来源:views.py

示例8: ListCache

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import get [as 别名]
class ListCache(object):

    DB_FILE = 'listing_db.json'
    DB_TTL = timedelta(hours=12)

    def __init__(self):
        self.db = TinyDB(os.path.join(os.path.join(os.getcwd(), os.path.dirname(__file__)), ListCache.DB_FILE))

    @property
    def db(self):
        return self._db

    @db.setter
    def db(self, db):
        self._db = db

    def listing_in_cache(self, listing):
        lquery = Query()
        return self.db.contains(lquery.hsh == listing.hsh)

    def retrieve_listing(self, listing):
        lquery = Query()
        list_dict = self.db.get(lquery.hsh == listing.hsh)
        return Listing.from_dict(list_dict)

    def insert_listing(self, listing):
        if self.listing_in_cache(listing):
            self.update_listing(listing)
        else:
            list_dict = listing.as_dict()
            list_dict['last_updated'] = datetime.now().isoformat()
            list_dict['hsh'] = listing.hsh
            self.db.insert(list_dict)

    def remove_listing(self, listing):
        lquery = Query()
        self.db.remove(lquery.hsh == listing.hsh)

    def update_listing(self, listing):
        lquery = Query()
        if self.listing_in_cache(listing):
            self.remove_listing(listing)
        self.insert_listing(listing)

    def remove_old_listings(self):
        list_ar = self.db.all()
        for listing in list_ar:
            if datetime.strptime(listing['last_updated'], '%Y-%m-%dT%H:%M:%S.%f') < datetime.now() - ListCache.DB_TTL:
                self.remove_listing(Listing.from_dict(listing))
开发者ID:althor880,项目名称:househunt,代码行数:51,代码来源:househunt.py

示例9: NumberStore

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import get [as 别名]
class NumberStore():
    def __init__(self, filename):
        self.db = TinyDB(filename)

    def initNumber(self, number):
        if not self.getNumberDict(number):
            self.db.insert({'number': number, 'accesses': [], 'info': '#yolo'})

    def touchNumber(self, number):
        self.initNumber(number)

        #print(self.getNumberDict(number))
        #accesses = self.getNumberDict(number)['accesses'].append(datetime.datetime.now())

        #self.db.update({'accesses': accesses}, where('number') == number)

    def getNumberDict(self, number):
        return self.db.get(where('number') == number)

    def getNumberList(self):
        return (entry['number'] for entry in self.db.all())

    def getAccesses(self, number):
        # if not number in self.db['numbers']:
        #     return None
        # if not 'info' in self.db['numbers'][number]:
        #     return None
        #
        # return self.db['numbers'][number]['info']
        return []

    def getInfo(self, number):
        return self.getNumberDict(number)['info']

    def setInfo(self, number, info):
        self.initNumber(number)
        self.db.update({'info': info}, where('number') == number)

        print(self.db.all())

    def deleteNumber(self, number):
        self.db.remove(where('number') == number)

        print(self.db.all())

    def close(self):
        self.db.close()
开发者ID:jackwillis,项目名称:numbertrack,代码行数:49,代码来源:numberstore.py

示例10: latest_run

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import get [as 别名]
def latest_run():
    form = SearchForm()
    annotateRunForm = AnnotateRunForm()

    db = TinyDB(recipyGui.config.get('tinydb'))

    runs = db.all()
    runs = sorted(runs, key = lambda x: parse(x['date'].replace('{TinyDate}:', '')), reverse=True)
    r = db.get(eid=runs[0].eid)
    diffs = db.table('filediffs').search(Query().run_id == r.eid)

    db.close()

    return render_template('details.html', query='', form=form, run=r,
                           annotateRunForm=annotateRunForm,
                           dbfile=recipyGui.config.get('tinydb'), diffs=diffs,
                           active_page='latest_run')
开发者ID:pablo-esteban,项目名称:recipy,代码行数:19,代码来源:views.py

示例11: __init__

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import get [as 别名]
class FolderManager:
    def __init__(self, path):
        self.db_file = os.path.join(path, CONF_DIR, FOLDER_DB_FN)
        self._db = TinyDB(self.db_file)

    def open_db(self):
        self._db = TinyDB(self.db_file)

    def close_db(self):
        self._db.close()

    def add_folder(self, file_name):
        if not self.folder_exists(file_name):
            entry = {'file_name': file_name}
            self._db.insert(entry)

    def get_all_entries(self):
        return self._db.all()

    def folder_exists(self, file_name):
        """ checks if a folder has been added """
        entries = self._db.search(where('file_name') == file_name)
        if entries:
            return True
        else:
            return False

    def remove_element(self, file_name):
        self._db.remove(where('file_name') == file_name)

    def get_file_names(self):
        """ returns all the file names of folders that the user has added """
        file_names = []
        for entry in self._db.all():
            file_names.append(entry['file_name'])
        return file_names

    def get_folder_by_name(self, expected_name):
        """ get documents by the specified property """
        entry = self._db.get(where('file_name') == expected_name)
        return entry

    def clear_all(self):
        self._db.purge()
开发者ID:Lingotek,项目名称:filesystem-connector,代码行数:46,代码来源:managers.py

示例12: test_json_readwrite

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import get [as 别名]
def test_json_readwrite():
    """
    Regression test for issue #1
    """
    # Create TinyDB instance
    db = TinyDB(path, policy='autoadd', storage=SFTPStorage)

    item = {'name': 'A very long entry'}
    item2 = {'name': 'A short one'}

    get = lambda s: db.get(where('name') == s)

    db.insert(item)
    assert get('A very long entry') == item

    db.remove(where('name') == 'A very long entry')
    assert get('A very long entry') is None

    db.insert(item2)
    assert get('A short one') == item2

    db.remove(where('name') == 'A short one')
    assert get('A short one') is None
开发者ID:emanjavacas,项目名称:canister,代码行数:25,代码来源:test_sftp_storage.py

示例13: TerritoryMapController

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import get [as 别名]
class TerritoryMapController(BaseController):
    def __init__(self):
        self.addresses = TinyDB(self.databaseDirectory + '/addresses.json')
        self.territories = TinyDB(self.databaseDirectory + '/territories.json')

    def get(self):
        territories = self.territories.all()

        marked = {}

        for territory in territories:
            territory_addresses = territory['addresses']
            points = []
            for address in territory_addresses:
                point = self.addresses.get(where('id') == address)
                address_full_name = point['address'] + ', ' + point['city']
                points.append({'x': point['cords'][0], 'y': point['cords'][1]})
            points.sort(key=lambda x: x['x'], reverse=True)
            points.sort(key=lambda x: x['y'])

            marked[territory['id']] = points

        return marked
开发者ID:kkalamarski,项目名称:Territorries,代码行数:25,代码来源:TerritoryMapController.py

示例14: save

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import get [as 别名]
def save():
    db = TinyDB('db.json')
    player_stats = db.table(name_input)
    if db.get(where('name') == name_input):
        player_stats.update({'time_advance' : player.time_advance}, eids=[1])
        player_stats.update({'bow_message': player.bow_message}, eids=[2])
        player_stats.update({'hunt_message': player.hunt_message}, eids=[3])
        player_stats.update({'can_hunt': player.can_hunt}, eids=[4])
        player_stats.update({'exploration1_message': player.exploration1_message}, eids=[5])
        player_stats.update({'sword_message': player.sword_message}, eids=[6])
        player_stats.update({'can_go_to_town': player.can_go_to_town}, eids=[7])
        player_stats.update({'health': player.health}, eids=[8])
        player_stats.update({'weapon': player.weapon}, eids=[9])
        player_stats.update({'energy': player.energy}, eids=[10])
        player_stats.update({'exploration_count': player.exploration_count}, eids=[11])
        player_stats.update({'town_count': player.town_count}, eids=[12])
        player_stats.update({'money': player.money}, eids=[13])
        player_stats.update(player.inventory, eids=[14])
        print "Saved"

    else:
        player_stats.insert({'time_advance' : player.time_advance})
        player_stats.insert({'bow_message': player.bow_message})
        player_stats.insert({'hunt_message': player.hunt_message})
        player_stats.insert({'can_hunt': player.can_hunt})
        player_stats.insert({'exploration1_message': player.exploration1_message})
        player_stats.insert({'sword_message': player.sword_message})
        player_stats.insert({'can_go_to_town': player.can_go_to_town})
        player_stats.insert({'health': player.health})
        player_stats.insert({'weapon': player.weapon})
        player_stats.insert({'energy': player.energy})
        player_stats.insert({'exploration_count': player.exploration_count})
        player_stats.insert({'town_count': player.town_count})
        player_stats.insert({'money': player.money})
        player_stats.insert(player.inventory)
        db.insert({'name' : name_input})
        print "First save"
开发者ID:frg100,项目名称:Sobreviure,代码行数:39,代码来源:Sobreviure_save.py

示例15: test_cutom_mapping_type_with_json

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import get [as 别名]
def test_cutom_mapping_type_with_json(tmpdir):
    from tinydb.database import Mapping

    class CustomDocument(Mapping):
        def __init__(self, data):
            self.data = data

        def __getitem__(self, key):
            return self.data[key]

        def __iter__(self):
            return iter(self.data)

        def __len__(self):
            return len(self.data)

    # Insert
    db = TinyDB(str(tmpdir.join('test.db')))
    db.purge()
    db.insert(CustomDocument({'int': 1, 'char': 'a'}))
    assert db.count(where('int') == 1) == 1

    # Insert multiple
    db.insert_multiple([
        CustomDocument({'int': 2, 'char': 'a'}),
        CustomDocument({'int': 3, 'char': 'a'})
    ])
    assert db.count(where('int') == 1) == 1
    assert db.count(where('int') == 2) == 1
    assert db.count(where('int') == 3) == 1

    # Write back
    doc_id = db.get(where('int') == 3).doc_id
    db.write_back([CustomDocument({'int': 4, 'char': 'a'})], [doc_id])
    assert db.count(where('int') == 3) == 0
    assert db.count(where('int') == 4) == 1
开发者ID:msiemens,项目名称:tinydb,代码行数:38,代码来源:test_tinydb.py


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