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


Python TinyDB.table方法代码示例

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


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

示例1: __init__

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import table [as 别名]
    def __init__(self):
        self.sentCache = {}
        self.checkingThread = threading.Thread(target = self.startThread)
        #self.checkingThread.daemon = True
        self.keepChecking = True
        self.config = Config()

        if self.config.winning_streak:
            self.winning_streak_messages = self.read_spree_file(self.config.winning_streak_file)
        if self.config.losing_streak:
            self.losing_streak_messages = self.read_spree_file(self.config.losing_streak_file)

        # Debug purposes
        self.printOutput = False

        # Initializing the API
        key = dotamatch.get_key()  # Steam Dev Key (~/.steamapi)
        try:
            self.match_history = MatchHistory(key)
            self.match_details = MatchDetails(key)
            self.account_details = PlayerSummaries(key)
            self.heroes = Heroes(key).heroes()

            # ActualDB
            db = TinyDB(self.config.db_path)
            #db.purge()
            #db.purge_tables()

            self.matches_table = db.table('matches')
            self.matches_info_table = db.table('matches_info')
        except dotamatch.api.ApiError:
            print u"Erro ao conectar à API."
开发者ID:leonardobsjr,项目名称:D2WBot,代码行数:34,代码来源:D2WBot_Utils.py

示例2: EventModel

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import table [as 别名]
class EventModel(object):
    def __init__(self, uri):
        self.uri = uri
        self.db = None
        self.reload()

    def reload(self):
        if self.db is not None:
            self.db.close()
        self.db = TinyDB(self.uri, indent=2)
        self.actions = self.db.table('actions')
        self.alarms = self.db.table('alarms')

    def get_action_by_id(self, action_id):
        return self.actions.get(eid=action_id)

    def get_alarm_by_id(self, alarm_id):
        return self.alarms.get(eid=alarm_id)

    def get_actions_by_alarm(self, alarm):
        for action_id in alarm.get('actions', []):
            action = self.get_action_by_id(action_id)
            if action is None: continue
            yield action

    def get_all_alarms(self):
        return self.alarms.all()

    def get_all_actions(self):
        return self.actions.all()

    def get_all_alarms_expanded(self):
        for alarm in self.get_all_alarms():
            for action in self.get_actions_by_alarm(alarm):
                yield alarm, action

    def add_event(self, alarm, actions):
        action_ids = [self.add_action(a) for a in actions]
        alarm['actions'] = action_ids
        return self.alarms.insert(alarm)

    def add_action(self, action):
        return self.actions.insert(action)

    def add_alarm(self, alarm):
        return self.add_event(alarm, [])

    def update_alarm(self, alarmid, new_fields={}):
        return self.alarms.update(new_fields, eids=[alarmid])

    def update_action(self, actionid, new_fields={}):
        return self.actions.update(new_fields, eids=[actionid])

    def delete_alarm(self, alarmid):
        return self.alarms.remove(eids=[alarmid])

    def delete_action(self, actionid):
        return self.actions.remove(eids=[actionid])
开发者ID:boyska,项目名称:larigira,代码行数:60,代码来源:event.py

示例3: load_db

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import table [as 别名]
def load_db(bot, conn):
    """Load in our database and the Headers."""
    global CACHE, USERS, LORE, COLLECTIONS, LINKS, DB_Q, HEADERS
    CACHE = TinyDB('destiny.json')
    USERS = CACHE.table('users')
    LORE = CACHE.table('lore')
    COLLECTIONS = CACHE.table('collections')
    LINKS = CACHE.table('links')
    DB_Q = Query()  # This is our query object used. Use it in all queries.
    HEADERS = {'X-API-Key': bot.config.get('api_keys', {}).get('destiny', None)}
开发者ID:JacobCallahan,项目名称:CloudBot,代码行数:12,代码来源:destiny.py

示例4: LocalCollectionStore

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

    def __init__(self):
        if TinyDB.DEFAULT_STORAGE == JSONStorage:
            self._db = TinyDB(path=self.path)
        else:
            self._db = TinyDB()

    def add(self, piece):
        """
        :param Piece piece:
        :return:
        """
        self._piece_table().insert(piece.to_dict())

    def piece_list(self):
        """
        :rtype: list(Piece)
        """

        return [Piece.from_dict(piece_dict) for piece_dict in self._piece_table().all()]

    @contract
    def state_list(self):
        """
        :rtype: list(WatchState)
        """
        state_entry_list = self._state_table().all()
        if not state_entry_list:
            return []

        return jsonpickle.loads(state_entry_list[0]['pickle'])

    def set_state_list(self, state_list):
        """
        :type state_list: list(WatchState)
        """
        state_table = self._state_table()
        state_table.purge()
        self._state_table().insert({'pickle': jsonpickle.dumps(state_list)})

    def _piece_table(self):
        return self._db.table("piece")

    def _state_table(self):
        return self._db.table("state")

    def _state_entry(self):
        Entry = Query()
        entry_search_list = self._state_table().search(Entry.name == "state_list")
        if entry_search_list:
            return entry_search_list[0]
开发者ID:AltarBeastiful,项目名称:rateItSeven,代码行数:54,代码来源:local_collection_store.py

示例5: __init__

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import table [as 别名]
    def __init__(self, path):

        root_dir = os.path.abspath(path)
        if not os.path.exists(root_dir):
            raise IOError('Path does not exist: %s' % path)

        fs = HashFS(os.path.join(root_dir, 'hashfs'), depth=3,
                    width=2, algorithm='md5')

        # Setup Serialisation for non list/dict objects
        serialization_store = SerializationMiddleware()
        serialization_store.register_serializer(DateTimeSerializer(),
                                                'TinyDate')
        serialization_store.register_serializer(FileSerializer(fs),
                                                'TinyFile')
        if opt.has_numpy:
            serialization_store.register_serializer(NdArraySerializer(),
                                                    'TinyArray')
        if opt.has_pandas:
            serialization_store.register_serializer(DataFrameSerializer(),
                                                    'TinyDataFrame')
            serialization_store.register_serializer(SeriesSerializer(),
                                                    'TinySeries')

        db = TinyDB(os.path.join(root_dir, 'metadata.json'),
                    storage=serialization_store)

        self.db = db
        self.runs = db.table('runs')
        self.fs = fs
开发者ID:elanmart,项目名称:sacred,代码行数:32,代码来源:tinydb_hashfs.py

示例6: prelimsearchURLs

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import table [as 别名]
def prelimsearchURLs():
    db = TinyDB('db.json')
    prelimtable = db.table('prelimcasedetails')
    cases = getAllSearchResults()
    prelimtable.purge()
    for idx, case in enumerate(cases):
        prelimtable.insert({'caseid': case.caseid, 'casename': case.casename, 'prelimvideourl': case.videourl,'detailedVideoURL':'0'})
开发者ID:unni88,项目名称:texascscraper,代码行数:9,代码来源:test.py

示例7: ArtemisApplication

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import table [as 别名]
class ArtemisApplication(Application):
    def __init__(self, db_file, *args, **kwargs):
        super(ArtemisApplication, self).__init__(*args, **kwargs)
        self._db = TinyDB(db_file)

    def merge_host(self, host):
        specs = filter(lambda (hostrx, _): hostrx.pattern == host, self.handlers)
        map(self.handlers.remove, specs)
        self.add_handlers(host, reduce(add, [s for _, s in specs]))

    def table(self, tname):
        return self._db.table(tname)

    def model(self, model_name):
        def _outer(model_cls):
            model_cls.__table__ = self.table(model_name)

            self.add_handlers('.*', [
                (r'/{}'.format(model_name),
                 ModelBaseRequest, dict(model=model_cls)),
                (r'/{}/query'.format(model_name),
                 ModelQueryRequest, dict(model=model_cls)),
                (r'/{}/([a-zA-Z\-_0-9]+)'.format(model_name),
                 ModelIDRequest, dict(model=model_cls)),
                (r'/{}/([a-zA-Z\-_0-9]+)/([a-zA-Z\-_0-9]+)'.format(model_name),
                 ModelMethodRequest, dict(model=model_cls))
            ])

            return model_cls

        return _outer
开发者ID:oakfang,项目名称:artemis,代码行数:33,代码来源:app.py

示例8: Repository

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import table [as 别名]
class Repository(Singleton):
    USERS_TABLE = 'users'
    USERS_RANK_TABLE = 'users_rank_stat'

    """ Repository class """
    def __init__(self):
        self.database = None

    def init_db(self, dbfile):
        """ Init repository """
        serialization = SerializationMiddleware()
        serialization.register_serializer(DateTimeSerializer(), 'TinyDate')
        self.database = TinyDB(dbfile, storage=serialization)

    def user_exists(self, wg_id):
        """ Check users exists """
        user = Query()
        count = self.database.table(Repository.USERS_TABLE).count(user.wg_id == wg_id)
        return count > 0

    def save_user(self, user_obj):
        """ Update user """
        table = self.database.table(Repository.USERS_TABLE)
        query = Query()
        users = table.search(query.wg_id == user_obj.wg_id)
        if len(users) > 0:
            existing = DbUser.fromdict(users[0])
            existing.last_date = user_obj.last_date
            table.update(existing.__dict__, query.wg_id == existing.wg_id)
        else:
            table.insert(user_obj.__dict__)

    def all_users(self):
        """ Get all users """
        table = self.database.table(Repository.USERS_TABLE)
        users_data = table.all()
        users = list()
        for item in users_data:
            users.append(DbUser.fromdict(item))
        return users

    def rank_history(self, wg_id):
        """ Get all rank history records """
        table = self.database.table(Repository.USERS_RANK_TABLE)
        query = Query()
        return table.search(query.wg_id == wg_id)
开发者ID:nixxa,项目名称:wows-rating,代码行数:48,代码来源:repository.py

示例9: test_purge_table

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import table [as 别名]
def test_purge_table():
    db = TinyDB(storage=MemoryStorage)
    assert [TinyDB.DEFAULT_TABLE] == list(db.tables())

    db.purge_table(TinyDB.DEFAULT_TABLE)
    assert [] == list(db.tables())

    table_name = 'some-other-table'
    db = TinyDB(storage=MemoryStorage)
    db.table(table_name)
    assert set([TinyDB.DEFAULT_TABLE, table_name]) == db.tables()

    db.purge_table(table_name)
    assert set([TinyDB.DEFAULT_TABLE]) == db.tables()

    db.purge_table('non-existent-table-name')
    assert set([TinyDB.DEFAULT_TABLE]) == db.tables()
开发者ID:drmaize,项目名称:compvision,代码行数:19,代码来源:test_tinydb.py

示例10: db_smartcache

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import table [as 别名]
def db_smartcache():
    db_ = TinyDB(storage=MemoryStorage)
    db_.purge_tables()

    db_.table_class = SmartCacheTable
    db_ = db_.table('_default')

    db_.insert_multiple({'int': 1, 'char': c} for c in 'abc')
    return db_
开发者ID:alapini,项目名称:tinydb-smartcache,代码行数:11,代码来源:test_smartcache.py

示例11: getdetailedSearchURL

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import table [as 别名]
def getdetailedSearchURL():
    db = TinyDB('db.json')
    prelimtable = db.table('prelimcasedetails')
    query = Query()
    elementstoupdate = prelimtable.search(query.detailedVideoURL == '0')
    for iter,element in enumerate(elementstoupdate):
        prelimURL = element['prelimvideourl']
        detailedVideoURL = getvideosourceinfo(prelimURL)
        caseid = element['caseid']
        prelimtable.update({'detailedVideoURL':detailedVideoURL},Query()['caseid'] == caseid)
开发者ID:unni88,项目名称:texascscraper,代码行数:12,代码来源:test.py

示例12: patched_modules

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import table [as 别名]
def patched_modules():
    db = TinyDB(recipyGui.config.get('tinydb'))
    modules = db.table('patches').all()
    db.close()

    form = SearchForm()

    return render_template('patched_modules.html', form=form,
                           active_page='patched_modules', modules=modules,
                           dbfile=recipyGui.config.get('tinydb'))
开发者ID:pablo-esteban,项目名称:recipy,代码行数:12,代码来源:views.py

示例13: test_gc

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import table [as 别名]
def test_gc(tmpdir):
    # See https://github.com/msiemens/tinydb/issues/92
    path = str(tmpdir.join('db.json'))
    db = TinyDB(path)
    table = db.table('foo')
    table.insert({'something': 'else'})
    table.insert({'int': 13})
    assert len(table.search(where('int') == 13)) == 1
    assert table.all() == [{'something': 'else'}, {'int': 13}]
    db.close()
开发者ID:msiemens,项目名称:tinydb,代码行数:12,代码来源:test_tinydb.py

示例14: MainView

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import table [as 别名]
class MainView(Frame):
    def __init__(self, parent):
        "docstring"
        Frame.__init__(self, parent)

        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("Pycollect")
        self.pack(fill=BOTH)

        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)

        filemenu = Menu(menubar)
        filemenu.add_command(label="Open", command=self.open_database)
        filemenu.add_command(label="Exit", command=self.on_exit)
        menubar.add_cascade(label="File", menu=filemenu)

        frame1 = Frame(self)
        frame1.pack(fill=X)
        self.game_count = StringVar()
        game_count_label = Label(frame1, textvariable=self.game_count).pack()

        frame2 = Frame(self)
        frame2.pack(fill=X, side=LEFT, expand=True)
        self.game_list = Listbox(frame2)
        self.game_list.pack(fill=Y, side=LEFT, expand=True)

        # Events
        self.bind('<<update_game_count>>', self.update_game_count)
        self.bind('<<update_game_list>>', self.update_game_list)

    def on_exit(self):
        self.quit()

    def open_database(self):
        filename = tkFileDialog.askopenfilename(filetypes=[('Database files', '.db'), ('All files', '.*')])
        self.db = TinyDB(filename)
        self.games = self.db.table('games')
        print len(self.games)
        self.event_generate('<<update_game_count>>')
        self.event_generate('<<update_game_list>>')

    def update_game_count(self, args):
        self.game_count.set('Game total: {}'.format(len(self.games)))

    def update_game_list(self, args):
        self.game_list.delete(0, END)
        game_titles = [g['name'] for g in self.games.all()]
        for title in game_titles:
            self.game_list.insert(END, title)
开发者ID:numkem,项目名称:pycollect,代码行数:55,代码来源:pycollect-tk.py

示例15: Database

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

    def get_user_value(self, user, key):
        key = '_' + key
        table = self.db.table('user_values')
        value = table.get(where('id') == user.id)
        try:
            return value[key]
        except KeyError:
            return None

    def set_user_value(self, user, key, value):
        self.insert_else_update_user(user, {key: value})

    def insert_else_update_user(self, user, extra_params=None):
        table = self.db.table('user_values')
        if not table.get(where('id') == user.id):
            table.insert({
                'id': user.id,
                'username': user.username,
                'first_name': user.first_name,
                'last_name': user.last_name
            })
        else:
            table.update({
                'username': user.username,
                'first_name': user.first_name,
                'last_name': user.last_name,
            }, where('id') == user.id)
        if extra_params:
            for k in extra_params:
                new_key = k if k.startswith('_') else '_' + k
                extra_params[new_key] = extra_params.pop(k)
            table.update(extra_params, where('id') == user.id)

    def process_message(self, message):
        if message.from_user:
            self.insert_else_update_user(message.from_user)
开发者ID:TheReverend403,项目名称:Pyper,代码行数:42,代码来源:database.py


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