本文整理汇总了Python中CodernityDB.database.Database.get方法的典型用法代码示例。如果您正苦于以下问题:Python Database.get方法的具体用法?Python Database.get怎么用?Python Database.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类CodernityDB.database.Database
的用法示例。
在下文中一共展示了Database.get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from CodernityDB.database import Database [as 别名]
# 或者: from CodernityDB.database.Database import get [as 别名]
class cache :
"""
cache for word morphological analysis
"""
def __init__(self,):
"""
Create Analex Cache
"""
self.cache={'checkedWords':{},
'FreqWords':{'noun':{}, 'verb':{},'stopword':{}},
};
self.db = Database('/tmp/qalsadiCache')
if not self.db.exists():
self.db.create();
x_ind = WithAIndex(self.db.path, 'a')
self.db.add_index(x_ind)
else:
self.db.open();
def __del__(self):
"""
Delete instance and clear cache
"""
self.cache=None;
self.db.close();
def isAlreadyChecked(self, word):
try:
return bool(self.db.get('a', word))
except: return False
#~ except: return False;
def getChecked(self, word):
x = self.db.get('a', word, with_doc=True)
y= x.get('doc',False);
if y: return y.get('d',[])
else: return []
def addChecked(self, word, data):
idata = {"a":word,'d':data}
self.db.insert(idata)
def existsCacheFreq(self, word, wordtype):
return word in self.cache['FreqWords'];
def getFreq(self, originalword, wordtype):
return self.cache['FreqWords'][wordtype].get(originalword,0);
def addFreq(self, original, wordtype, freq):
self.cache['FreqWords'][wordtype][original]=freq;
示例2: main
# 需要导入模块: from CodernityDB.database import Database [as 别名]
# 或者: from CodernityDB.database.Database import get [as 别名]
def main():
db = Database('/tmp/tut2')
db.create()
x_ind = WithXIndex(db.path, 'x')
db.add_index(x_ind)
for x in xrange(100):
db.insert(dict(x=x))
for y in xrange(100):
db.insert(dict(y=y))
print db.get('x', 10, with_doc=True)
示例3: main
# 需要导入模块: from CodernityDB.database import Database [as 别名]
# 或者: from CodernityDB.database.Database import get [as 别名]
def main():
db = Database('db/tut2')
if db.exists():
db.open()
else:
db.create()
x_ind = WithXIndex(db.path, 'y')
db.add_index(x_ind)
for x in xrange(100):
db.insert(dict(x=x))
for y in xrange(100):
db.insert(dict(y=y))
print db.get('x', 10, with_doc=True)
示例4: BenchCodernityDB
# 需要导入模块: from CodernityDB.database import Database [as 别名]
# 或者: from CodernityDB.database.Database import get [as 别名]
class BenchCodernityDB(BenchBase):
ID_FIELD = "_id"
def __init__(self, *args, **kwargs):
super(BenchCodernityDB, self).__init__(*args, **kwargs)
def create_database(self):
self.db = Database(self.db_name)
self.db.create()
self.db.add_index(WithSmallNumberIndex(self.db.path, "small_number"))
def delete_database(self):
self.db.close()
shutil.rmtree(self.db_name)
def create(self, record):
self.db.insert(record)
def get(self, key):
return self.db.get("id", key, with_doc=True)
def query(self, **kwargs):
key, val = kwargs.items()[0]
return list(self.db.get_many(key, val, limit=-1, with_doc=True))
示例5: main
# 需要导入模块: from CodernityDB.database import Database [as 别名]
# 或者: from CodernityDB.database.Database import get [as 别名]
def main():
db = Database('/tmp/tut4')
db.create()
x_ind = WithXIndex(db.path, 'x')
db.add_index(x_ind)
for x in xrange(100):
db.insert(dict(x=x))
for y in xrange(100):
db.insert(dict(y=y))
print db.get('x', 10, with_doc=True)
for curr in db.get_many('x', start=15, end=25, limit=-1, with_doc=True):
print curr
示例6: test_insert_get
# 需要导入模块: from CodernityDB.database import Database [as 别名]
# 或者: from CodernityDB.database.Database import get [as 别名]
def test_insert_get(self, tmpdir, sh_nums):
db = Database(str(tmpdir) + '/db')
db.create(with_id_index=False)
n = globals()['ShardedUniqueHashIndex%d' % sh_nums]
db.add_index(n(db.path, 'id'))
l = []
for x in xrange(10000):
l.append(db.insert(dict(x=x))['_id'])
for curr in l:
assert db.get('id', curr)['_id'] == curr
示例7: __init__
# 需要导入模块: from CodernityDB.database import Database [as 别名]
# 或者: from CodernityDB.database.Database import get [as 别名]
class SecuIn:
'''
Handles all data input into the database
'''
def __init__(self,passkey):
self.key = passkey
self.initQuestions = SecuQ(self.key)
self.DBConfig = AppConfig()
self.dbName = self.DBConfig.mapget('databaseinfo')['databasename']
self.db = Database(self.dbName)
initDay = DayEntry(self.key) # checks day hash or creates a new one
self.dayKey = initDay.dayKey
def questionDataIN(self,data):
'''
Data IN:
{'a' : 2, 'b': 14 , 'c': 11, 'd': 43, 'note' : 'hello'}
or
{ 'b': 14 , 'c': 11, 'd': 43, 'note' : 'hello'}
some entries may be missing
Data OUT: (NEVER DELETE ANYTIHNG :) )
{'date' : xx , _id: ###date2### , 'a':{'xxdate3xx':2},
'b':{'xxdate3xx':14},
'c':{'xxdate3xx':11},
'note':{'xxdate3xx':'you'}}
{'date' : xx , _id: ###date1### , 'a':{'xxdate1xx':1,'xxdate2xx':2},
'b':{'xxdate1xx':14,'xxdate2xx':14},
'c':{'xxdate1xx':11,'xxdate2xx':11},
'note':{'xxdate2xx':'hello','xxdate3xx':'you'}
'''
timeIN = getTimeStamp() #get now time
#initialize new questions
# get data, as doc {'date':'xx/xx/xxTxx:xx:xxxx','question1':'x','question2':'x'}, same as dic format
if(self.db.exists()):
self.db.open()
self.db.id_ind.enc_key = self.key
dayrow = self.db.get('id', self.dayKey, with_doc=True)
#this function assumes database already opened
# this is gonna be a tuple that is inserted directly
#convert data from javasript to python dict/json
# if (type(data) is str):
dataIN=eval(data) #{ 'b': 14 , 'c': 11, 'd': 43, 'note' : 'hello'}
datachanged = dataIN.keys()
for question in datachanged:
try:
dayrow[question][timeIN] = dataIN[question]
except KeyError: #first write to key, initiate
dayrow[question] = {}
dayrow[question][timeIN] = dataIN[question]
self.db.update(dayrow)
self.db.close()
self.initQuestions.questionsValidate(datachanged) #insert questions whos data had changed
#if all ok!
return True
示例8: CodernityDB
# 需要导入模块: from CodernityDB.database import Database [as 别名]
# 或者: from CodernityDB.database.Database import get [as 别名]
class CodernityDB(BaseService):
"""A service providing a codernity db interface."""
name = 'db'
default_config = dict(db=dict(path=''), app=dict(dir=''))
def __init__(self, app):
super(CodernityDB, self).__init__(app)
self.dbfile = os.path.join(self.app.config['app']['dir'],
self.app.config['db']['path'])
self.db = None
self.uncommitted = dict()
self.stop_event = Event()
self.db = Database(self.dbfile)
try:
log.info('opening db', path=self.dbfile)
self.db.open()
except DatabasePathException:
log.info('db does not exist, creating it', path=self.dbfile)
self.db.create()
self.db.add_index(MD5Index(self.dbfile, 'key'))
def _run(self):
self.stop_event.wait()
def stop(self):
# commit?
log.info('closing db')
if self.started:
self.db.close()
self.stop_event.set()
def get(self, key):
log.debug('getting entry', key=key)
if key in self.uncommitted:
if self.uncommitted[key] is None:
raise KeyError("key not in db")
return self.uncommitted[key]
try:
value = self.db.get('key', key, with_doc=True)['doc']['value']
except RecordNotFound:
raise KeyError("key not in db")
return compress.decompress(value)
def put(self, key, value):
log.debug('putting entry', key=key, value=value)
self.uncommitted[key] = value
def commit(self):
log.debug('committing', db=self)
for k, v in self.uncommitted.items():
if v is None:
doc = self.db.get('key', k, with_doc=True)['doc']
self.db.delete(doc)
else:
self.db.insert({'key': k, 'value': compress.compress(v)})
self.uncommitted.clear()
def delete(self, key):
log.debug('deleting entry', key=key)
self.uncommitted[key] = None
def __contains__(self, key):
try:
self.get(key)
except KeyError:
return False
return True
def __eq__(self, other):
return isinstance(other, self.__class__) and self.db == other.db
def __repr__(self):
return '<DB at %d uncommitted=%d>' % (id(self.db), len(self.uncommitted))
def inc_refcount(self, key, value):
self.put(key, value)
def dec_refcount(self, key):
pass
def revert_refcount_changes(self, epoch):
pass
def commit_refcount_changes(self, epoch):
pass
def cleanup(self, epoch):
pass
def put_temporarily(self, key, value):
self.inc_refcount(key, value)
self.dec_refcount(key)
示例9: Store
# 需要导入模块: from CodernityDB.database import Database [as 别名]
# 或者: from CodernityDB.database.Database import get [as 别名]
class Store():
def __init__(self, pathname):
self.store_path = os.path.join(pathname, "store")
self.objects_counter = {}
self.init_store_db()
if not os.path.exists(self.store_path):
os.mkdir(self.store_path)
def init_store_dir(self):
if not os.path.exists(self.store_path):
os.mkdir(self.store_path)
objects_path = os.path.join(self.store_path, "objects")
if not os.path.exists(objects_path):
os.mkdir(objects_path)
backups_path = os.path.join(self.store_path, "backups")
if not os.path.exists(backups_path):
os.mkdir(backups_path)
journal_path = os.path.join(self.store_path, "journal")
if not os.path.exists(journal_path):
os.mkdir(journal_path)
journal_objects_path = os.path.join(self.store_path, "journal/objects")
if not os.path.exists(journal_objects_path):
os.mkdir(journal_objects_path)
journal_backups_path = os.path.join(self.store_path, "journal/backups")
if not os.path.exists(journal_backups_path):
os.mkdir(journal_backups_path)
def init_store_db(self):
self.db = Database(os.path.join(self.store_path, "store.db"))
if not self.db.exists():
self.db.create()
self.db.add_index(WithHashIndex(self.db.path, "hash"))
self.db.add_index(WithPointerIndex(self.db.path, "pointer"))
else:
self.db.open()
def get_path(self):
return self.store_path #volania napr. BackupObject.new...(... , target.get_path())
def get_backup_path(self, backup_name):
backup_path = os.path.join(self.store_path, "backups")
return os.path.join(backup_path, backup_name)
def get_journal_backup_path(self, backup_name):
backup_path = os.path.join(self.get_journal_path(), "backups")
return os.path.join(backup_path, backup_name)
def get_journal_backup_path(self, backup_name):
backup_path = os.path.join(self.get_journal_path(), "backups")
return os.path.join(backup_path, backup_name)
def get_objet_dir_path(self, hash):
return os.path.join(self.store_path, "objects", hash[:2])
def get_object_path(self, hash):
object_path = os.path.join(self.store_path, "objects", hash[:2])
return os.path.join(object_path, hash + ".data")
def get_journal_object_path(self, hash):
object_path = os.path.join(self.get_journal_path(), "objects", hash[:2])
if not os.path.exists(object_path):
os.mkdir(object_path)
return os.path.join(object_path, hash + ".data")
def get_journal_tmp_object_path(self, hash):
object_path = os.path.join(self.get_journal_path(), "objects")
return os.path.join(object_path, hash + ".data")
def get_object_header_path(self, hash):
object_header_path = os.path.join(self.store_path, "objects", hash[:2])
return os.path.join(object_header_path, hash + ".meta")
def get_journal_object_header_path(self, hash):
object_header_path = os.path.join(self.get_journal_path(), "objects", hash[:2])
if not os.path.exists(object_header_path):
os.mkdir(object_header_path)
return os.path.join(object_header_path, hash + ".meta")
def get_journal_tmp_object_header_path(self, hash):
object_header_path = os.path.join(self.get_journal_path(), "objects")
return os.path.join(object_header_path, hash + ".meta")
def get_backups_path(self):
return os.path.join(self.store_path, "backups")
def get_latest_path(self):
latest_tmp_path = os.path.join(self.store_path, "backups")
return os.path.join(latest_tmp_path, "latest")
def get_journal_latest_path(self):
latest_tmp_path = os.path.join(self.get_journal_path(), "backups")
return os.path.join(latest_tmp_path, "latest")
def get_journal_path(self):
return os.path.join(self.store_path, "journal")
def get_all_backups(self):
backups_path = os.path.join(self.store_path, "backups")
backups = os.listdir(backups_path)
#.........这里部分代码省略.........
示例10: __init__
# 需要导入模块: from CodernityDB.database import Database [as 别名]
# 或者: from CodernityDB.database.Database import get [as 别名]
custom_header = """from CodernityDB.tree_index import MultiTreeBasedIndex
from itertools import izip"""
def __init__(self, *args, **kwargs):
kwargs['key_format'] = '16s'
super(TreeMultiTest, self).__init__(*args, **kwargs)
self.__l = kwargs.get('w_len', 2)
def make_key_value(self, data):
name = data['w']
l = self.__l
max_l = len(name)
out = set()
for x in xrange(l - 1, max_l):
m = (name, )
for y in xrange(0, x):
m += (name[y + 1:],)
out.update(set(''.join(x).rjust(16, '_').lower() for x in izip(*m))) #ignore import error
return out, dict(w=name)
def make_key(self, key):
return key.rjust(16, '_').lower()
db = Database('./tmp/multi')
db.create()
db.add_index(TreeMultiTest(db.path, "words"))
db.insert(dict(w='Codernity'))
print db.get('words', 'dern')['w'] # "Codernity"
print db.get('words', 'cod')['w'] # "Codernity"
示例11: questionGet
# 需要导入模块: from CodernityDB.database import Database [as 别名]
# 或者: from CodernityDB.database.Database import get [as 别名]
class SecuQ:
'''
Abstract:
Handles all Questions, input and output input into the database
def questionGet(self):
- reloads all question database attributes
def questionInsert(self,data,descriptor='inclusive'):
-> data = input question dict
ex:
'a':{'active':'True','typ':'slider','range':'0-100','aggregate':True, 'multipoint':True}, ,,,,.................
- inclusive = Updates entried (overwrites) (safe)
- exclusive = deletes all entried not in input (dangerous)
def questionsValidate(self,data):
-> data = input list of questions [(keys)]
each question verified, if not initiated, will be initiated after
'''
def __init__(self,passkey):
self.key = passkey
self.indexdb = DBIndexSystem(self.key)
#self.indexdb.masterIndex
#self.indexdb.Qindex
#self.indexdb.Tindex
#self.indexdb.IndexedTable
#self.indexdb.dbName
self.db = Database(self.indexdb.dbName)
#init variables blank, avoid key errors
self.all = {}
self.valid = {}
self.active = {}
self.notactive = {}
self.unInit = {}
self.typ = {}
self.aggregate = {}
self.multipoint = {}
self.questionGet() #populate variables
#query: all , valid, true,unInit, false, inline
def questionGet(self): #the passkey in question should be loaded from config or index passkey
if(self.db.exists()):
self.db.open()
self.db.id_ind.enc_key = self.key
#select Qindex
Qindex = self.db.get('id', self.indexdb.Qindex, with_doc=True)
oQ = Qindex.copy()
# delete unnessesary to modify
# if u use del <key> it deletes all instances in all variables using same reference to dict
oQ.pop('_rev', None)
oQ.pop('_id', None)
oQ.pop('t', None)
#oQ.pop('questions', None)
#returns list in string for of all keys aka the question and metadata
#step through and assign
questionsSet = oQ.keys()
for question in questionsSet:
self.all[question] = oQ[question]
if oQ[question]['active'] == 'True':
self.active[question] = oQ[question]
if oQ[question]['active'] == 'unInit':
self.unInit[question] = oQ[question]
if (oQ[question]['active'] == 'unInit') | (oQ[question]['active'] == 'True'):
self.valid[question] = oQ[question]
#.........这里部分代码省略.........
示例12: main
# 需要导入模块: from CodernityDB.database import Database [as 别名]
# 或者: from CodernityDB.database.Database import get [as 别名]
def main():
db2 = pickledb.load('examlple.db', True)
db2.set('test', 'test')
db = Database('/home/papaja/Zaloha/target/store.db')
db.open()
# db.create()
# print database
# x_ind = WithHashIndex(db.path, 'hash')
# pointer_ind = WithHashIndex(db.path, 'pointer')
# db.add_index(x_ind)
# db.add_index(pointer_ind)
# db.insert({'hash':'3f8ee76c84d95c3f4ed061db98694be57e7d33da', 'pointer':1})
# # for x in xrange(100):
# db.insert(dict(x='3f8ee76c84d95c3f4ed061db98694be57e7d33da'))
# for curr in db.all('id'):
# curr['x'] = 1
# db.update(curr)
# print curr
for curr in db.all('id'):
print curr
try:
test = db.get('hash', '3f8ee76c84d95c3f4ed061db98694be57e7d33da', with_doc=True)
print test
except RecordNotFound:
print "Nieje rekord"
exit()
test['doc']['pointer'] = test['doc']['pointer'] + 1
db.update(test['doc'])
for curr in db.all('id'):
print curr
exit()
lstat = os.lstat("/home/papaja/.cache/keyring-SZ5Lrw/gpg")
mode = lstat.st_mode
if S_ISDIR(mode):
print("dir")
elif S_ISREG(mode):
print("file")
elif S_ISLNK(mode):
print("link")
else:
print("None")
print(mode)
print(lstat)
print(S_ISFIFO(mode))
exit()
#print(os.readlink('/home/papaja/Zaloha/target/objects/test'))
#shutil.move("/home/papaja/Zaloha/target/journal/objects/a3fe40b52ec03a7e2d8c8c0ca86baaf0192038c5.meta", "/home/papaja/Zaloha/target/objects")
#shutil.rmtree(os.path.join("/home/papaja/", "objects"))
# myFile = MyFile('/home/papaja/third')
# print(myFile.readline().decode("UTF-8"))
# dst = open('/home/mint/Diplomovka/first', 'wb')
# src = open('second', 'rb')
# synced = open('/home/papaja/third', 'wb')
# signatureFile = open('signature', 'wb')
# deltaFile = open('/home/papaja/delta', 'rb');
# hashes = pyrsync2.blockchecksums(dst)
# hashes_save = {
# weak: (index, strong) for index, (weak, strong)
# in enumerate(hashes)
# }
# signature.write(bytes('gz\n', "UTF-8"))
# pickle.dump(hashes_save, signature, pickle.HIGHEST_PROTOCOL)
# type = signature.readline().decode("UTF-8")
# print("Typ {}".format(type.strip()))
# signature.readline()
# hashes_save = pickle.load(signature)
# print(hashes_save)
# delta = pyrsync2.rsyncdelta(src, hashes_save)
# pyrsync2.patchstream(dst, synced, delta)
# io.FileIO
# signature = librsync.signature(dst)
# delta = librsync.delta(src, signature)
# librsync.patch(dst, delta, synced)
# synced.close()
temp = tempfile.NamedTemporaryFile()
skuska = open(temp.name, "wb")
dst = open('/home/mint/Diplomovka/first', 'rb')
velkost = open('/home/mint/Diplomovka/velkost', 'rb')
retazec = 'ahoj'
print(len(retazec))
print(velkost.readline())
print(velkost.read(3))
#velkost.write(str(sys.getsizeof(retazec)))
dst_data = dst.read(16)
while dst_data:
skuska.write(dst_data)
dst_data = dst.read(16)
skuska.close()
patchProcess = subprocess.Popen(['rdiff', 'patch', temp.name, '/home/mint/Diplomovka/delta'], stdout=subprocess.PIPE)
patchFile, patchError = patchProcess.communicate()
# print patchFile
# dst_data = dst.read(16)
while dst_data:
#patchProcess.stdin.write(dst_data)
dst_data = dst.read(16)
# # patchProcess.stdin.write(dst_data)
#patchProcess.stdin.write(dst_data)
#patchProcess.stdin.close()
#.........这里部分代码省略.........
示例13: __init__
# 需要导入模块: from CodernityDB.database import Database [as 别名]
# 或者: from CodernityDB.database.Database import get [as 别名]
custom_header = 'from CodernityDB.sharded_hash import ShardedHashIndex'
def __init__(self, *args, **kwargs):
kwargs['sh_nums'] = 10
kwargs['key_format'] = 'I'
kwargs['use_make_keys'] = True
super(MySharded, self).__init__(*args, **kwargs)
def make_key_value(self, data):
return data['x'], None
def calculate_shard(self, key):
return key % self.sh_nums
y = 1500 * 'y'
db = Database('/tmp/shard')
db.create(with_id_index=False)
db.add_index(CustomIdSharded(db.path, 'id'))
db.add_index(MySharded(db.path, 'x'))
# it makes non sense to use sharding with such small number of records
for x in xrange(10 ** 4):
db.insert({'x': x, 'y': y})
print db.get('x', random.randint(0, 10 ** 4))['_id']
示例14: __init__
# 需要导入模块: from CodernityDB.database import Database [as 别名]
# 或者: from CodernityDB.database.Database import get [as 别名]
class cache :
"""
cache for word morphological analysis
"""
DB_PATH = os.path.join(os.path.expanduser('~'), '.thaalabCache')
def __init__(self, cache_path=False):
"""
Create Analex Cache
"""
# use this dictionary as a local cache,
# The global db will be updated on destructing object
# get the database path
if hasattr(sys, 'frozen'): # only when running in py2exe this exists
base = sys.prefix
else: # otherwise this is a regular python script
base = os.path.dirname(os.path.realpath(__file__))
if not cache_path:
file_path = self.DB_PATH
else:
file_path = os.path.join(os.path.dirname(cache_path), '.thaalabCache')
self.cache={};
self.db = Database(file_path)
if not self.db.exists():
self.db.create();
x_ind = WithAIndex(self.db.path, 'a')
self.db.add_index(x_ind)
else:
self.db.open();
def __del__(self):
"""
Delete instance and clear cache
"""
self.cache=None;
self.db.close();
def update(self):
"""update data base """
#~ pass
for word in self.cache:
self.add_checked(word, self.cache[word])
def is_already_checked(self, word):
try:
return bool(self.db.get('a', word))
except:
return False
#~ except: return False;
def get_checked(self, word):
try:
x = self.db.get('a', word, with_doc=True)
y = x.get('doc',False);
if y:
return y.get('d',[])
else: return []
except:
return []
def add_checked(self, word, data):
idata = {"a":word,'d':data}
try:
saved = self.db.get('a', word, with_doc=True)
except:
saved = False
if saved:
saved['doc']['d'] = data
doc = saved['doc']
doc['update'] = True
self.db.update(doc)
else:
self.db.insert(idata)
def exists_cache_word(self, word):
""" test if word exists in cache"""
#if exists in cache dictionary
if word in self.cache:
return True
else: # test in database
if self.is_already_checked(word):
stored_data = self.get_checked(word)
self.cache[word] = stored_data
return bool(self.cache[word])
else:
# add null dict to the word index to avoid multiple database check
self.cache[word] = {}
return {}
def get_relation_freq(self, word_prev, word_cur, relation):
self.exists_cache_word(word_prev)
return self.cache.get(word_prev, {}).get(word_cur, {}).get(relation, 0);
def is_related(self, word_prev, word_cur):
""" test if two words are related"""
#serach in cache
self.exists_cache_word(word_prev)
#.........这里部分代码省略.........
示例15: __init__
# 需要导入模块: from CodernityDB.database import Database [as 别名]
# 或者: from CodernityDB.database.Database import get [as 别名]
class SecuFrame: #in producion, key must be specified
def __init__(self,passkey,date_range='all'):
self.key = passkey
self.Qeng = SecuQ(self.key)
self.indexdb = DBIndexSystem(self.key)
#self.indexdb.masterIndex
#self.indexdb.Qindex
#self.indexdb.Tindex
#self.indexdb.IndexedTable
#self.indexdb.dbName
self.dayindex = DayEntry(self.key)
#self.dayindex.dayKey
self.DBConfig = AppConfig()
self.dbName = self.DBConfig.mapget('databaseinfo')['databasename']
self.db = Database(self.dbName)
self.dbparseable = self.db2json(daterange=date_range,clean=True)
def __del__(self):
if (self.db.opened):
self.db.close()
def db2json(self,daterange,clean=True):
'''
> daterange
- tuple datetime objects to specify range
(dateObj,dateObj)
'''
dfJSON = []
if(self.db.exists()):
self.db.open()
self.db.id_ind.enc_key = self.key
if daterange == "all":
if clean == True:
for currHash in self.indexdb.IndexedTable: #get row
curr = self.db.get('id', currHash, with_doc=True)
curr.pop('_id')
curr.pop('_rev')
dfJSON.append(curr)
self.db.close()
return dfJSON
if clean == False:
for currHash in self.indexdb.IndexedTable: #get row
curr = self.db.get('id', currHash, with_doc=True)
dfJSON.append(curr)
self.db.close()
return dfJSON
if daterange == "today":
if clean == True:
curr = self.db.get('id', self.dayindex.dayKey, with_doc=True)
curr.pop('_id')
curr.pop('_rev')
dfJSON.append(curr)
self.db.close()
return dfJSON
'''
#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
if ((type(daterange) == tuple) & (len(daterange)<=2) & (daterange[0]<daterange[1]) &(type(daterange[0])==datetime.datetime) & (type(daterange[1])==datetime.datetime): #if it's a valid daterange
if clean == True
for curr in db.all('id'): #get row
currdto=dt.datetime.strptime(curr['date'],"%Y-%m-%d %H:%M:%S.%f")
if ( daterange[0] <= currdto <= daterange[1]):
curr.pop('_id')
curr.pop('_rev')
dfJSON.append(curr)
db.close()
return dfJSON
if clean == False:
#.........这里部分代码省略.........