本文整理汇总了Python中tinydb.TinyDB.insert方法的典型用法代码示例。如果您正苦于以下问题:Python TinyDB.insert方法的具体用法?Python TinyDB.insert怎么用?Python TinyDB.insert使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tinydb.TinyDB
的用法示例。
在下文中一共展示了TinyDB.insert方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_serialisation_of_pandas_dataframe
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import insert [as 别名]
def test_serialisation_of_pandas_dataframe(tmpdir):
from sacred.observers.tinydb_hashfs import (DataFrameSerializer,
SeriesSerializer)
from tinydb_serialization import SerializationMiddleware
import numpy as np
import pandas as pd
# Setup Serialisation object for non list/dict objects
serialization_store = SerializationMiddleware()
serialization_store.register_serializer(DataFrameSerializer(),
'TinyDataFrame')
serialization_store.register_serializer(SeriesSerializer(),
'TinySeries')
db = TinyDB(os.path.join(tmpdir.strpath, 'metadata.json'),
storage=serialization_store)
df = pd.DataFrame(np.eye(3), columns=list('ABC'))
series = pd.Series(np.ones(5))
document = {
'foo': 'bar',
'some_dataframe': df,
'nested': {
'ones': series
}
}
db.insert(document)
returned_doc = db.all()[0]
assert returned_doc['foo'] == 'bar'
assert (returned_doc['some_dataframe'] == df).all().all()
assert (returned_doc['nested']['ones'] == series).all()
示例2: download
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import insert [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()
示例3: test_json_readwrite
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import insert [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
示例4: AddUser
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import insert [as 别名]
def AddUser(self, username, chatid):
my_pokemon = [0] * 152 # Matching arr index to pokemon index (0 is disregarded)
db = TinyDB('users.json')
db.insert({'username': username, 'chatid': chatid, 'pokemon': my_pokemon})
pass # RETURN: check bool
示例5: dragon_greet
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import insert [as 别名]
def dragon_greet():
print("_______________________________________________________________\n")
time = datetime.datetime.now().time()
global user_full_name
global user_prefix
global config_file
command = "getent passwd $LOGNAME | cut -d: -f5 | cut -d, -f1"
user_full_name = os.popen(command).read()
user_full_name = user_full_name[:-1] # .decode("utf8")
home = expanduser("~")
config_file = TinyDB(home + '/.dragonfire_config.json')
callme_config = config_file.search(Query().datatype == 'callme')
if callme_config:
user_prefix = callme_config[0]['title']
else:
gender_config = config_file.search(Query().datatype == 'gender')
if gender_config:
user_prefix = GENDER_PREFIX[gender_config[0]['gender']]
else:
gender = Classifier.gender(user_full_name.split(' ', 1)[0])
config_file.insert({'datatype': 'gender', 'gender': gender})
user_prefix = GENDER_PREFIX[gender]
if time < datetime.time(12):
time_of_day = "morning"
elif datetime.time(12) < time < datetime.time(18):
time_of_day = "afternoon"
else:
time_of_day = "evening"
userin.execute(["echo"], "To activate say 'Dragonfire!' or 'Wake Up!'")
userin.say(" ".join(["Good", time_of_day, user_prefix]))
示例6: test_serialisation_of_numpy_ndarray
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import insert [as 别名]
def test_serialisation_of_numpy_ndarray(tmpdir):
from sacred.observers.tinydb_hashfs import NdArraySerializer
from tinydb_serialization import SerializationMiddleware
import numpy as np
# Setup Serialisation object for non list/dict objects
serialization_store = SerializationMiddleware()
serialization_store.register_serializer(NdArraySerializer(), 'TinyArray')
db = TinyDB(os.path.join(tmpdir.strpath, 'metadata.json'),
storage=serialization_store)
eye_mat = np.eye(3)
ones_array = np.ones(5)
document = {
'foo': 'bar',
'some_array': eye_mat,
'nested': {
'ones': ones_array
}
}
db.insert(document)
returned_doc = db.all()[0]
assert returned_doc['foo'] == 'bar'
assert (returned_doc['some_array'] == eye_mat).all()
assert (returned_doc['nested']['ones'] == ones_array).all()
示例7: crawl
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import insert [as 别名]
def crawl(sr=0, er=3):
archive = dict()
url = "https://community.topcoder.com/tc?module=ProblemArchive&sr=%d&er=%d" % (sr, er)
print "requesting seed page..."
r = requests.get(url)
html = h.unescape(r.content.decode('utf-8'))
doc = pq(html)
for i in doc('table.paddingTable2').eq(2).children()[3:]:
round_name = pq(i).children().eq(2).find('a').text()
sub_url = pq(i).children().eq(2).find('a').attr.href
if sub_url is not None:
rid = sub_url.split('rd=')[-1]
archive[round_name] = {'rid': rid, 'round': round_name}
db = TinyDB("data/db.json")
tot = len(archive.values())
cur = 0
prob_cnt = 0
for k in archive.values():
problems = crawl_round(k['rid'], k['round'])
print 'parse result:'
for p in problems:
for pk, pv in p.items():
print "%-15s: %s" % (pk, pv)
prob_cnt += 1
q = Query()
if not db.search(q.name == p['name']):
print '>>>>>>> insert problem: %s' % p['name']
db.insert(p)
print '-' * 10
cur += 1
print '*' * 10, 'finish', k['round'], ',tot rounds:', tot, 'cur round:', cur, 'round problems:', len(problems), '*' * 10
print 'done, total round: %d, total problems: %d' % (cur, prob_cnt)
示例8: __init__
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import insert [as 别名]
class pcDB:
def __init__(self,table="default"):
#'/path/to/db.json'
path=''
self.table=table
self.db = TinyDB(path).table(table)
def insert(self,_dict):
'''
:return:
'''
self.db.insert(_dict)
# db.insert({'int': 1, 'char': 'a'})
# db.insert({'int': 1, 'char': 'b'})
pass
def getAll(self):
'''
not param just get all data
:return:
'''
return self.db.all()
#db.search()
pass
pass
#
# from tinydb.storages import JSONStorage
# from tinydb.middlewares import CachingMiddleware
# db = TinyDB('/path/to/db.json', storage=CachingMiddleware(JSONStorage))
示例9: insert_test
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import insert [as 别名]
def insert_test(db_file='db.json'):
db = TinyDB(db_file)
db.insert({
'name': 'Aman Verma',
'items': 1,
'contact': 7890701597
})
示例10: process_and_add_one
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import insert [as 别名]
def process_and_add_one(pdf_path):
pdf_name = pdf_path.split("/")
pdf_name = pdf_name[-1]
directory = pdf_path[0 : -len(pdf_name)]
stripped_name = pdf_name[0:-4]
title_path = title_dir + "/" + stripped_name + ".xml"
extract_title(pdf_path, title_path)
# check if title extraction worked, otherwise stop with this one
tf = open(title_path, "r")
txml = tf.read()
if txml == "title extraction failed":
return None
# build dictionary with info we've got
tf = open(title_path, "r")
txml = tf.read()
txml = txml.split(">")
title = "title not found"
for line in txml:
if "</title" in line:
title = line[0:-7]
print title
break
# save nice text version of title
txt_name_path = title_path[0:-4] + ".txt"
ftxt = open(txt_name_path, "a")
ftxt.write(title)
if title == "title not found":
return None
# if title was found, get DOI from it
currDOI = get_DOI_from_title(title)
# open/create tiny db
db = TinyDB(db_loc)
# make sure the paper isnt in the db already
paper = Query()
gotit = db.search(paper.ownDOI == currDOI)
if gotit:
return currDOI
text_path_xml = text_dir + "/" + stripped_name + ".xml"
text_path_txt = text_dir + "/" + stripped_name + ".txt"
if not extract_text(pdf_path, text_path_xml, text_path_txt):
print ("text extraction failed")
return None
# only extract bibtex if you don't have it already, because this is the long part
# TODO: Return before doing bib extraction
bib_path = bib_dir + "/" + stripped_name + ".bib"
if not extract_bibtex(pdf_path, bib_path):
print ("caught in the new code")
return None
refDOIs = get_ref_list_DOIs(bib_path)
new_dict = {"ownDOI": currDOI, "refDOIs": refDOIs, "filename": stripped_name}
db.insert(new_dict)
return currDOI
示例11: test_gc
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import insert [as 别名]
def test_gc(tmpdir):
# See https://github.com/msiemens/tinydb/issues/92
path = str(tmpdir.join('db.json'))
table = TinyDB(path).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}]
示例12: write
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import insert [as 别名]
def write(message, args):
# message.reply('I can understand hi or HI!')
# react with thumb up emoji
#message.react('+1')
db = TinyDB('db.json')
db.insert({'value': args});
print args
db.close()
示例13: test_json_kwargs
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import insert [as 别名]
def test_json_kwargs(tmpdir):
db_file = tmpdir.join('test.db')
db = TinyDB(str(db_file), sort_keys=True, indent=4, separators=(',', ': '))
# Write contents
db.insert({'b': 1})
db.insert({'a': 1})
assert db_file.read() == '''{
示例14: obj_func_range
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import insert [as 别名]
def obj_func_range(self, func, bounds=[(0.8, 1.2), (0.8, 1.2)], x_r=6,
args=(), comps=None, vary='rs'):
import numpy
from tinydb import TinyDB
import logging
x_range = numpy.linspace(bounds[0][0], bounds[0][1], x_r)
y_range = numpy.linspace(bounds[1][0], bounds[1][1], x_r)
xg, yg = numpy.meshgrid(x_range, y_range)
func_r = numpy.zeros((x_r, x_r))
func_ed = numpy.zeros((x_r, x_r))
func_es = numpy.zeros((x_r, x_r))
func_eph = numpy.zeros((x_r, x_r))
func_ee = numpy.zeros((x_r, x_r))
func_ex = numpy.zeros((x_r, x_r))
for i in range(xg.shape[0]):
for j in range(yg.shape[0]):
X = [xg[i, j], yg[i, j]] # [x_1, x_2]
f_out = func(X, *args) # Scalar outputs
func_r[i, j] = numpy.float64(f_out)
func_ed[i, j] = numpy.float64(self.Epsilon_d)
func_es[i, j] = numpy.float64(self.Epsilon_s)
func_eph[i, j] = numpy.float64(self.Epsilon_ph)
func_ee[i, j] = numpy.float64(self.Epsilon_e)
func_ex[i, j] = numpy.float64(self.Epsilon_x)
if False:
print('self.Epsilon_d = {}'.format(self.Epsilon_d))
print('self.Epsilon_s = {}'.format(self.Epsilon_s))
print('self.Epsilon_ph = {}'.format(self.Epsilon_ph))
print('self.Epsilon_e = {}'.format(self.Epsilon_e))
print('self.Epsilon_x = {}'.format(self.Epsilon_x))
# Save results
plot_kwargs = {'func_r' : func_r,
'xg' : xg,
'yg' : yg,
'func_ed' : func_ed,
'func_es' : func_es,
'func_eph' : func_eph,
'func_ee' : func_ee,
'func_ex' : func_ex,
}
if False:
# TODO: Find an easy way to store multidimensional numpy arrays
db = TinyDB('.db/p_obj_db.json')
db_store = {'dtype' : 'p_obj_r',
'comps' : comps,
'bounds' : bounds,
'x_r' : x_r,
'vary' : vary,
'plot_kwargs' : plot_kwargs}
db.insert(db_store)
return plot_kwargs
示例15: test_serializer_nondestructive
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import insert [as 别名]
def test_serializer_nondestructive(tmpdir):
path = str(tmpdir.join('db.json'))
serializer = SerializationMiddleware(JSONStorage)
serializer.register_serializer(DateTimeSerializer(), 'TinyDate')
db = TinyDB(path, storage=serializer)
data = {'date': datetime.utcnow(), 'int': 3}
data_before = dict(data) # implicitly copy
db.insert(data)
assert data == data_before