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


Python TinyDB.update方法代码示例

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


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

示例1: download

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import update [as 别名]
def download(name,force=False):
    db=TinyDB(path_db_)
    temp = Query()
    data=requests.get("https://raw.githubusercontent.com/PyThaiNLP/pythainlp-corpus/master/db.json")
    data_json=data.json()
    if name in list(data_json.keys()):
        temp_name=data_json[name]
        print("Download : "+name)
        if len(db.search(temp.name==name))==0:
            print(name+" "+temp_name['version'])
            download_(temp_name['download'],temp_name['file_name'])
            db.insert({'name': name, 'version': temp_name['version'],'file':temp_name['file_name']})
        else:
            if len(db.search(temp.name==name and temp.version==temp_name['version']))==0:
                print("have update")
                print("from "+name+" "+db.search(temp.name==name)[0]['version']+" update to "+name+" "+temp_name['version'])
                yes_no="y"
                if force==False:
                    yes_no=str(input("y or n : ")).lower()
                if "y"==yes_no:
                    download_(temp_name['download'],temp_name['file_name'])
                    db.update({'version':temp_name['version']},temp.name==name)
            else:
                print("re-download")
                print("from "+name+" "+db.search(temp.name==name)[0]['version']+" update to "+name+" "+temp_name['version'])
                yes_no="y"
                if force==False:
                    yes_no=str(input("y or n : ")).lower()
                if "y"==yes_no:
                    download_(temp_name['download'],temp_name['file_name'])
                    db.update({'version':temp_name['version']},temp.name==name)
    db.close()
开发者ID:zkan,项目名称:pythainlp,代码行数:34,代码来源:__init__.py

示例2: log_output

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import update [as 别名]
def log_output(filename, source):
    filename = os.path.abspath(filename)
    if option(CONFIG, 'general', 'debug'):
        print("Output to %s using %s" % (filename, source))
    #Update object in DB
    db = TinyDB(DBFILE)
    db.update(append("outputs", filename), eids=[RUN_ID])
    db.close()
开发者ID:benlewis-tes,项目名称:recipy,代码行数:10,代码来源:log.py

示例3: hide_all

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import update [as 别名]
def hide_all():
    db = TinyDB(DB_FILENAME)
    eids = [
        r.eid for r in db.search(
            (Query().hidden == False) & (Query().starred == False)
        )
    ]
    db.update({'hidden': True}, eids=eids)
    db.close()
    return 'OK'
开发者ID:modrzew,项目名称:gumtree-scraper,代码行数:12,代码来源:server.py

示例4: annotate

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import update [as 别名]
def annotate():
    notes = request.form['notes']
    run_id = int(request.form['run_id'])

    query = request.args.get('query', '')

    db = TinyDB(recipyGui.config.get('tinydb'))
    db.update({'notes': notes}, eids=[run_id])
    db.close()

    return redirect(url_for('run_details', id=run_id, query=query))
开发者ID:pablo-esteban,项目名称:recipy,代码行数:13,代码来源:views.py

示例5: RemovePokemon

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import update [as 别名]
    def RemovePokemon(self, username, chatid, pokemon):
        db = TinyDB('users.json')
        Username = Query()
        user = db.search((Username.username == username) &  (Username.chatid == chatid))
        # print(pokemon)
        my_pokemon_cur = user[0]['pokemon'][pokemon]
        # print(my_pokemon_cur)
        my_pokemon_new = self.DecrementPokeArr(user[0]['pokemon'], pokemon)
        # print (my_pokemon_new)
        db.update({'pokemon': my_pokemon_new}, ((Username.username == username ) & (Username.chatid == chatid)))

        pass # RETURN: check bool
开发者ID:bcc5160,项目名称:PokeBot,代码行数:14,代码来源:tinydb_interface.py

示例6: TinyDBStore

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import update [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

示例7: Test_003_Modify_existing_data_by_valid_query_Function

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import update [as 别名]
class Test_003_Modify_existing_data_by_valid_query_Function(unittest.TestCase):
	def setUp(self):
		self.db = TinyDB('db.json')

	def tearDown(self):
		self.db.purge()
		self.db.all()

	def test_simple_modify_valid_exist(self):
		print("case 3 modify existing data by valid query")
		self.db.insert({'Name': 'Greg', 'Email': '[email protected]', 'int' : 1, 'char':1})
		self.db.update({'int': 10}, where('Name') == 'Greg')
		result=self.db.search(where('Name') == 'Greg')
		self.assertEqual(result,[{'Name': 'Greg', 'Email': '[email protected]', 'int' : 10, 'char':1}])
开发者ID:lexihan0209,项目名称:softwareTesting,代码行数:16,代码来源:testiny.py

示例8: NumberStore

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import update [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

示例9: Test_006_Modify_Not_existing_data_by_valid_query_Function

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import update [as 别名]
class Test_006_Modify_Not_existing_data_by_valid_query_Function(unittest.TestCase):
	def setUp(self):
		self.db = TinyDB('db.json')

	def tearDown(self):
		self.db.purge()
		self.db.all()

	def test_simple_modify_not_exist(self):
		print("case 6 modify Non-existing data by valid query")
		result=self.db.update({'int': 10}, where('Name') == 'Wendy')
		self.assertEqual(result,None)
开发者ID:lexihan0209,项目名称:softwareTesting,代码行数:14,代码来源:testiny.py

示例10: batch_update

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import update [as 别名]
def batch_update(info):
    db = TinyDB('db.json')
    rows = {(i['contestId'], i['index']): i for i in db.all()}
    insert = {}
    update = {}
    print "Calculating insert row & update row"
    for k, v in info.items():
        if rows.get(k, None) is None:
            insert[k] = v
        elif rows[k]['isSolved'] != v['isSolved']:
            update[k] = {'isSolved': v['isSolved'], 'name': v['name']}
    print "Calculation finish, %d rows going to be inserted, %d rows going to be updated" % \
        (len(insert.keys()), len(update.keys()))
    raw_input("Press any key to continue.")
    problem = Query()
    for v in insert.values():
        print "insert row: %d, %s, %s" % (v['contestId'], v['index'], v['name'])
        db.insert(v)
    for k, v in update.items():
        print "update row: %d, %s, %s, solved: %r" % (k[0], k[1], v['name'], v['isSolved'])
        db.update(v, (problem.contestId == k[0]) & (problem.index == k[1]))
    print 'Done!'
开发者ID:AplusB,项目名称:ACEveryDay,代码行数:24,代码来源:update_problems.py

示例11: finish

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import update [as 别名]
def finish(dirname):
    fnames = []
    for f in ls(dirname):
        if f.split('.')[-1] == 'cpp':
            fnames.append(f)
    if not path.exists('./Archive/%s' % dirname):
        pathname = './Archive/%s' % dirname
        makedirs(pathname)
        print '>>>> create directory:[%s]' % pathname

    db = TinyDB("data/db.json")
    for f in fnames:
        oldpath = '%s/%s' % (dirname, f)
        newpath = './Archive/%s/%s' % (dirname, f)
        move(oldpath, newpath)
        print '>>>> move [%s] to [%s]' % (oldpath, newpath)
        q = Query()
        pname = path.splitext(f)[0]
        if db.search(q.name == pname):
            db.update({'solved': True}, (q.name == pname))
            print '>>>> db update, problem: `%s` solved' % pname
    rmtree(dirname)
开发者ID:eggeek,项目名称:topcoder,代码行数:24,代码来源:update.py

示例12: update

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import update [as 别名]
def update():
    db = TinyDB("data/db.json")
    cur = './Archive'
    problems = []
    for f in ls(cur):
        if f in ignore:
            continue
        if f.startswith('.'):
            continue
        if not path.isdir(cur + '/' + f):
            continue
        # print 'find round: %s' % f
        for problem_name in ls(cur + '/' + f):
            problems.append(problem_name.split('.')[0])
    counter = 0
    for p in problems:
        q = Query()
        dp = db.search(q.name == p)
        if (len(dp) > 0 and dp[0]['solved'] is False):
            print 'db update, problem :`%s` solved' % p
            db.update({'solved': True}, (q.name == p))
            counter += 1
    print '>>>> %d rows have been updated.' % counter
开发者ID:eggeek,项目名称:topcoder,代码行数:25,代码来源:update.py

示例13: output

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import update [as 别名]
def output(x):
    print("")
    print(x)


db = TinyDB("summaries.json")

# cleanup:
db.purge()


# insert

db.insert({"type": "apple", "count": 7})
db.insert({"type": "peach", "count": 3})

# query

output(db.all())
Fruit = Query()

output(db.search(Fruit.type == "peach"))
output(db.search(Fruit.count >= 3))

db.update({"count": 10}, Fruit.type == "apple")
output(db.search(Fruit.type == "apple"))

db.remove(Fruit.count < 5)
print(db.all())
开发者ID:podhmo,项目名称:individual-sandbox,代码行数:31,代码来源:main.py

示例14: __init__

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import update [as 别名]
class ProgramEngine:

    # pylint: disable=exec-used

    _instance = None

    def __init__(self):
        self._program = None
        self._log = ""
        self._programs = TinyDB("data/programs.json")
        query = Query()
        for dirname, dirnames, filenames, in os.walk(PROGRAM_PATH):
            dirnames
            for filename in filenames:
                if PROGRAM_PREFIX in filename:
                    program_name = filename[len(PROGRAM_PREFIX):-len(PROGRAM_SUFFIX)]
                    if self._programs.search(query.name == program_name) == []:
                        logging.info("adding program %s in path %s as default %r", program_name, dirname, ("default" in dirname))
                        self._programs.insert({"name": program_name, "filename": os.path.join(dirname, filename), "default": str("default" in dirname)})

    @classmethod
    def get_instance(cls):
        if not cls._instance:
            cls._instance = ProgramEngine()
        return cls._instance

    def prog_list(self):
        return self._programs.all()

    def save(self, program):
        query = Query()
        self._program = program
        program_db_entry = program.as_dict()
        program_db_entry["filename"] = os.path.join(PROGRAM_PATH, PROGRAM_PREFIX + program.name + PROGRAM_SUFFIX)
        if self._programs.search(query.name == program.name) != []:
            self._programs.update(program_db_entry, query.name == program.name)
        else:
            self._programs.insert(program_db_entry)
        f = open(program_db_entry["filename"], 'w+')
        json.dump(program.as_dict(), f)
        f.close()

    def load(self, name):
        query = Query()
        program_db_entries = self._programs.search(query.name == name)
        if program_db_entries != []:
            logging.info(program_db_entries[0])
            f = open(program_db_entries[0]["filename"], 'r')
            self._program = Program.from_dict(json.load(f))
        return self._program

    def delete(self, name):
        query = Query()
        program_db_entries = self._programs.search(query.name == name)
        if program_db_entries != []:
            os.remove(program_db_entries[0]["filename"])
            self._programs.remove(query.name == name)

    def create(self, name, code):
        self._program = Program(name, code)
        return self._program

    def is_running(self, name):
        return self._program.is_running() and self._program.name == name

    def check_end(self):
        return self._program.check_end()

    def log(self, text):
        self._log += text + "\n"

    def get_log(self):
        return self._log
开发者ID:CoderBotOrg,项目名称:coderbot,代码行数:75,代码来源:program.py

示例15: log_update

# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import update [as 别名]
def log_update(field, filename, source):
    filename = os.path.abspath(filename)
    print("Adding %s to %s using $s" % (field, filename, source))
    db = TinyDB(DBFILE)
    db.update(append(field, filename), eids=[RUN_ID])
    db.close()
开发者ID:benlewis-tes,项目名称:recipy,代码行数:8,代码来源:log.py


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