本文整理汇总了Python中anki.db.DB类的典型用法代码示例。如果您正苦于以下问题:Python DB类的具体用法?Python DB怎么用?Python DB使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DB类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Deck
def Deck(path, queue=True, lock=True):
"Open a new or existing deck. Path must be unicode."
path = os.path.abspath(path)
create = not os.path.exists(path)
if create:
base = os.path.basename(path)
for c in ("/", ":", "\\"):
assert c not in base
# connect
db = DB(path)
if create:
ver = _createDB(db)
else:
ver = _upgradeSchema(db)
db.execute("pragma cache_size = 20000")
# add db to deck and do any remaining upgrades
deck = _Deck(db)
if ver < CURRENT_VERSION:
_upgradeDeck(deck, ver)
elif create:
deck.addModel(BasicModel(deck))
deck.addModel(ClozeModel(deck))
# default to basic
deck.conf['currentModelId'] = 1
deck.save()
if lock:
deck.lock()
if not queue:
return deck
# rebuild queue
deck.reset()
return deck
示例2: operation_upload
def operation_upload(self, col, data, session):
# Verify integrity of the received database file before replacing our
# existing db.
temp_db_path = session.get_collection_path() + ".tmp"
with open(temp_db_path, "wb") as f:
f.write(data)
try:
test_db = DB(temp_db_path)
if test_db.scalar("pragma integrity_check") != "ok":
raise HTTPBadRequest("Integrity check failed for uploaded " "collection database file.")
test_db.close()
except sqlite.Error as e:
raise HTTPBadRequest("Uploaded collection database file is " "corrupt.")
# Overwrite existing db.
col.close()
try:
os.rename(temp_db_path, session.get_collection_path())
finally:
col.reopen()
# If everything went fine, run hook_upload if one is defined.
if self.hook_upload is not None:
self.hook_upload(col, session)
return True
示例3: download
def download(self):
runHook("sync", "download")
self.col.close()
cont = self.req("download")
tpath = self.col.path + ".tmp"
open(tpath, "wb").write(cont)
# check the received file is ok
d = DB(tpath)
assert d.scalar("pragma integrity_check") == "ok"
d.close()
# overwrite existing collection
os.unlink(self.col.path)
os.rename(tpath, self.col.path)
self.col = None
示例4: _loadMeta
def _loadMeta(self):
path = os.path.join(self.base, "prefs.db")
new = not os.path.exists(path)
def recover():
# if we can't load profile, start with a new one
os.rename(path, path+".broken")
QMessageBox.warning(
None, "Preferences Corrupt", """\
Anki's prefs.db file was corrupt and has been recreated. If you were using multiple \
profiles, please add them back using the same names to recover your cards.""")
try:
self.db = DB(path, text=str)
self.db.execute("""
create table if not exists profiles
(name text primary key, data text not null);""")
except:
recover()
return self._loadMeta()
if not new:
# load previously created
try:
self.meta = cPickle.loads(
self.db.scalar(
"select data from profiles where name = '_global'"))
return
except:
recover()
return self._loadMeta()
# create a default global profile
self.meta = metaConf.copy()
self.db.execute("insert or replace into profiles values ('_global', ?)",
cPickle.dumps(metaConf))
self._setDefaultLang()
return True
示例5: connect
def connect(self):
if self.col.server:
return
path = self.dir()+".db"
create = not os.path.exists(path)
self.db = DB(path)
if create:
self._initDB()
示例6: Collection
def Collection(path, lock=True, server=False, sync=True):
"Open a new or existing collection. Path must be unicode."
assert path.endswith(".anki2")
path = os.path.abspath(path)
create = not os.path.exists(path)
if create:
base = os.path.basename(path)
for c in ("/", ":", "\\"):
assert c not in base
# connect
db = DB(path)
if create:
ver = _createDB(db)
else:
ver = _upgradeSchema(db)
db.execute("pragma temp_store = memory")
if sync:
db.execute("pragma cache_size = 10000")
db.execute("pragma journal_mode = wal")
else:
db.execute("pragma synchronous = off")
# add db to col and do any remaining upgrades
col = _Collection(db, server)
if ver < SCHEMA_VERSION:
_upgrade(col, ver)
elif create:
# add in reverse order so basic is default
addClozeModel(col)
addBasicModel(col)
col.save()
if lock:
col.lock()
return col
示例7: connect
def connect(self):
if self.col.server:
return
path = self.dir()+".db2"
create = not os.path.exists(path)
os.chdir(self._dir)
self.db = DB(path)
if create:
self._initDB()
self.maybeUpgrade()
示例8: download
def download(self):
runHook("sync", "download")
localNotEmpty = self.col.db.scalar("select 1 from cards")
self.col.close()
cont = self.req("download")
tpath = self.col.path + ".tmp"
if cont == "upgradeRequired":
runHook("sync", "upgradeRequired")
return
open(tpath, "wb").write(cont)
# check the received file is ok
d = DB(tpath)
assert d.scalar("pragma integrity_check") == "ok"
remoteEmpty = not d.scalar("select 1 from cards")
d.close()
# accidental clobber?
if localNotEmpty and remoteEmpty:
os.unlink(tpath)
return "downloadClobber"
# overwrite existing collection
os.unlink(self.col.path)
os.rename(tpath, self.col.path)
self.col = None
示例9: _loadMeta
def _loadMeta(self):
opath = os.path.join(self.base, "prefs.db")
path = os.path.join(self.base, "prefs21.db")
if os.path.exists(opath) and not os.path.exists(path):
shutil.copy(opath, path)
new = not os.path.exists(path)
def recover():
# if we can't load profile, start with a new one
if self.db:
try:
self.db.close()
except:
pass
for suffix in ("", "-journal"):
fpath = path + suffix
if os.path.exists(fpath):
os.unlink(fpath)
QMessageBox.warning(
None, "Preferences Corrupt", """\
Anki's prefs21.db file was corrupt and has been recreated. If you were using multiple \
profiles, please add them back using the same names to recover your cards.""")
try:
self.db = DB(path)
assert self.db.scalar("pragma integrity_check") == "ok"
self.db.execute("""
create table if not exists profiles
(name text primary key, data text not null);""")
data = self.db.scalar(
"select cast(data as blob) from profiles where name = '_global'")
except:
recover()
return self._loadMeta()
if not new:
# load previously created data
try:
self.meta = self._unpickle(data)
return
except:
print("resetting corrupt _global")
# create a default global profile
self.meta = metaConf.copy()
self.db.execute("insert or replace into profiles values ('_global', ?)",
self._pickle(metaConf))
self._setDefaultLang()
return True
示例10: _loadMeta
def _loadMeta(self):
path = os.path.join(self.base, "prefs.db")
new = not os.path.exists(path)
self.db = DB(path, text=str)
self.db.execute("""
create table if not exists profiles
(name text primary key, data text not null);""")
if new:
# create a default global profile
self.meta = metaConf.copy()
self.db.execute("insert into profiles values ('_global', ?)",
cPickle.dumps(metaConf))
self._setDefaultLang()
return True
else:
# load previously created
self.meta = cPickle.loads(
self.db.scalar(
"select data from profiles where name = '_global'"))
示例11: _loadMeta
def _loadMeta(self):
path = os.path.join(self.base, "prefs.db")
new = not os.path.exists(path)
self.db = DB(path, text=str)
self.db.execute(
"""
create table if not exists profiles
(name text primary key, data text not null);"""
)
if not new:
# load previously created
try:
self.meta = cPickle.loads(self.db.scalar("select data from profiles where name = '_global'"))
return
except:
# if we can't load profile, start with a new one
os.rename(path, path + ".broken")
return self._loadMeta()
# create a default global profile
self.meta = metaConf.copy()
self.db.execute("insert or replace into profiles values ('_global', ?)", cPickle.dumps(metaConf))
self._setDefaultLang()
return True
示例12: run
def run(self):
db = DB(self.file)
ver = db.scalar(
"select value from global_variables where key='version'")
assert ver.startswith('Mnemosyne SQL 1') or ver == "2"
# gather facts into temp objects
curid = None
notes = {}
note = None
for _id, id, k, v in db.execute("""
select _id, id, key, value from facts f, data_for_fact d where
f._id=d._fact_id"""):
if id != curid:
if note:
notes[note['_id']] = note
note = {'_id': _id}
curid = id
note[k] = v
if note:
notes[note['_id']] = note
# gather cards
front = []
frontback = []
vocabulary = []
cloze = {}
for row in db.execute("""
select _fact_id, fact_view_id, tags, next_rep, last_rep, easiness,
acq_reps+ret_reps, lapses, card_type_id from cards"""):
# categorize note
note = notes[row[0]]
if row[1].endswith(".1"):
if row[1].startswith("1.") or row[1].startswith("1::"):
front.append(note)
elif row[1].startswith("2.") or row[1].startswith("2::"):
frontback.append(note)
elif row[1].startswith("3.") or row[1].startswith("3::"):
vocabulary.append(note)
elif row[1].startswith("5.1"):
cloze[row[0]] = note
# check for None to fix issue where import can error out
rawTags = row[2];
if rawTags is None:
rawTags = ""
# merge tags into note
tags = rawTags.replace(", ", "\x1f").replace(" ", "_")
tags = tags.replace("\x1f", " ")
if "tags" not in note:
note['tags'] = []
note['tags'] += self.col.tags.split(tags)
note['tags'] = self.col.tags.canonify(note['tags'])
# if it's a new card we can go with the defaults
if row[3] == -1:
continue
# add the card
c = ForeignCard()
c.factor = int(row[5]*1000)
c.reps = row[6]
c.lapses = row[7]
# ivl is inferred in mnemosyne
next, prev = row[3:5]
c.ivl = max(1, (next - prev)/86400)
# work out how long we've got left
rem = int((next - time.time())/86400)
c.due = self.col.sched.today+rem
# get ord
m = re.search(".(\d+)$", row[1])
ord = int(m.group(1))-1
if 'cards' not in note:
note['cards'] = {}
note['cards'][ord] = c
self._addFronts(front)
total = self.total
self._addFrontBacks(frontback)
total += self.total
self._addVocabulary(vocabulary)
self.total += total
self._addCloze(cloze)
self.total += total
self.log.append(ngettext("%d note imported.", "%d notes imported.", self.total) % self.total)
示例13: __init__
#.........这里部分代码省略.........
def _defaultBase(self):
if isWin:
loc = QStandardPaths.writableLocation(QStandardPaths.AppDataLocation)
return os.path.join(loc, "Anki2")
elif isMac:
return os.path.expanduser("~/Library/Application Support/Anki2")
else:
dataDir = os.environ.get(
"XDG_DATA_HOME", os.path.expanduser("~/.local/share"))
if not os.path.exists(dataDir):
os.makedirs(dataDir)
return os.path.join(dataDir, "Anki2")
def _loadMeta(self):
path = os.path.join(self.base, "prefs21.db")
new = not os.path.exists(path)
def recover():
# if we can't load profile, start with a new one
if self.db:
try:
self.db.close()
except:
pass
broken = path+".broken"
if os.path.exists(broken):
os.unlink(broken)
os.rename(path, broken)
QMessageBox.warning(
None, "Preferences Corrupt", """\
Anki's prefs21.db file was corrupt and has been recreated. If you were using multiple \
profiles, please add them back using the same names to recover your cards.""")
try:
self.db = DB(path)
self.db.execute("""
create table if not exists profiles
(name text primary key, data text not null);""")
except:
recover()
return self._loadMeta()
if not new:
# load previously created
try:
self.meta = pickle.loads(
self.db.scalar(
"select cast(data as blob) from profiles where name = '_global'"))
return
except:
recover()
return self._loadMeta()
# create a default global profile
self.meta = metaConf.copy()
self.db.execute("insert or replace into profiles values ('_global', ?)",
pickle.dumps(metaConf))
self._setDefaultLang()
return True
def ensureProfile(self):
"Create a new profile if none exists."
if self.firstRun:
self.create(_("User 1"))
p = os.path.join(self.base, "README.txt")
open(p, "w").write(_("""\
This folder stores all of your Anki data in a single location,
to make backups easy. To tell Anki to use a different location,
please see:
示例14: ProfileManager
#.........这里部分代码省略.........
def addonFolder(self):
return self._ensureExists(os.path.join(self.base, "addons"))
def backupFolder(self):
return self._ensureExists(
os.path.join(self.profileFolder(), "backups"))
def collectionPath(self):
return os.path.join(self.profileFolder(), "collection.anki2")
# Helpers
######################################################################
def _ensureExists(self, path):
if not os.path.exists(path):
os.makedirs(path)
return path
def _defaultBase(self):
if isWin:
s = QSettings(QSettings.UserScope, "Microsoft", "Windows")
s.beginGroup("CurrentVersion/Explorer/Shell Folders")
d = s.value("Personal")
return os.path.join(d, "Anki")
elif isMac:
return os.path.expanduser("~/Documents/Anki")
else:
return os.path.expanduser("~/Anki")
def _load(self):
path = os.path.join(self.base, "prefs.db")
new = not os.path.exists(path)
self.db = DB(path, text=str)
self.db.execute("""
create table if not exists profiles
(name text primary key, data text not null);""")
if new:
# create a default global profile
self.meta = metaConf.copy()
self.db.execute("insert into profiles values ('_global', ?)",
cPickle.dumps(metaConf))
self._setDefaultLang()
# and save a default user profile for later (commits)
self.create("User 1")
else:
# load previously created
self.meta = cPickle.loads(
self.db.scalar(
"select data from profiles where name = '_global'"))
def _pwhash(self, passwd):
return checksum(unicode(self.meta['id'])+unicode(passwd))
# Default language
######################################################################
# On first run, allow the user to choose the default language
def _setDefaultLang(self):
# the dialog expects _ to be defined, but we're running before
# setLang() has been called. so we create a dummy op for now
import __builtin__
__builtin__.__dict__['_'] = lambda x: x
# create dialog
class NoCloseDiag(QDialog):
示例15: __init__
#.........这里部分代码省略.........
return os.path.join(get_appdata(), "Anki2")
elif isMac:
return os.path.expanduser("~/Library/Application Support/Anki2")
else:
dataDir = os.environ.get(
"XDG_DATA_HOME", os.path.expanduser("~/.local/share"))
if not os.path.exists(dataDir):
os.makedirs(dataDir)
return os.path.join(dataDir, "Anki2")
def _loadMeta(self):
opath = os.path.join(self.base, "prefs.db")
path = os.path.join(self.base, "prefs21.db")
if os.path.exists(opath) and not os.path.exists(path):
shutil.copy(opath, path)
new = not os.path.exists(path)
def recover():
# if we can't load profile, start with a new one
if self.db:
try:
self.db.close()
except:
pass
for suffix in ("", "-journal"):
fpath = path + suffix
if os.path.exists(fpath):
os.unlink(fpath)
QMessageBox.warning(
None, "Preferences Corrupt", """\
Anki's prefs21.db file was corrupt and has been recreated. If you were using multiple \
profiles, please add them back using the same names to recover your cards.""")
try:
self.db = DB(path)
assert self.db.scalar("pragma integrity_check") == "ok"
self.db.execute("""
create table if not exists profiles
(name text primary key, data text not null);""")
data = self.db.scalar(
"select cast(data as blob) from profiles where name = '_global'")
except:
recover()
return self._loadMeta()
if not new:
# load previously created data
try:
self.meta = self._unpickle(data)
return
except:
print("resetting corrupt _global")
# create a default global profile
self.meta = metaConf.copy()
self.db.execute("insert or replace into profiles values ('_global', ?)",
self._pickle(metaConf))
self._setDefaultLang()
return True
def ensureProfile(self):
"Create a new profile if none exists."
if self.firstRun:
self.create(_("User 1"))
p = os.path.join(self.base, "README.txt")
open(p, "w").write(_("""\
This folder stores all of your Anki data in a single location,
to make backups easy. To tell Anki to use a different location,
please see: