本文整理汇总了Python中anki.db.DB.commit方法的典型用法代码示例。如果您正苦于以下问题:Python DB.commit方法的具体用法?Python DB.commit怎么用?Python DB.commit使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类anki.db.DB
的用法示例。
在下文中一共展示了DB.commit方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ProfileManager
# 需要导入模块: from anki.db import DB [as 别名]
# 或者: from anki.db.DB import commit [as 别名]
class ProfileManager(object):
def __init__(self, base=None, profile=None):
self.name = None
# instantiate base folder
self.base = base or self._defaultBase()
self.ensureLocalFS()
self.ensureBaseExists()
# load metadata
self.firstRun = self._loadMeta()
# did the user request a profile to start up with?
if profile:
try:
self.load(profile)
except TypeError:
raise Exception("Provided profile does not exist.")
# Base creation
######################################################################
def ensureLocalFS(self):
if self.base.startswith("\\\\"):
QMessageBox.critical(
None, "Error", """\
To use Anki on a network share, the share must be mapped to a local drive \
letter. Please see the 'File Locations' section of the manual for more \
information.""")
raise Exception("unc")
def ensureBaseExists(self):
try:
self._ensureExists(self.base)
except:
# can't translate, as lang not initialized
QMessageBox.critical(
None, "Error", """\
Anki can't write to the harddisk. Please see the \
documentation for information on using a flash drive.""")
raise
# Profile load/save
######################################################################
def profiles(self):
return sorted(
unicode(x, "utf8") for x in
self.db.list("select name from profiles")
if x != "_global")
def load(self, name, passwd=None):
prof = cPickle.loads(
self.db.scalar("select data from profiles where name = ?",
name.encode("utf8")))
if prof['key'] and prof['key'] != self._pwhash(passwd):
self.name = None
return False
if name != "_global":
self.name = name
self.profile = prof
return True
def save(self):
sql = "update profiles set data = ? where name = ?"
self.db.execute(sql, cPickle.dumps(self.profile),
self.name.encode("utf8"))
self.db.execute(sql, cPickle.dumps(self.meta), "_global")
self.db.commit()
def create(self, name):
prof = profileConf.copy()
self.db.execute("insert into profiles values (?, ?)",
name.encode("utf8"), cPickle.dumps(prof))
self.db.commit()
def remove(self, name):
shutil.rmtree(self.profileFolder())
self.db.execute("delete from profiles where name = ?",
name.encode("utf8"))
self.db.commit()
def rename(self, name):
oldName = self.name
oldFolder = self.profileFolder()
self.name = name
newFolder = self.profileFolder(create=False)
if os.path.exists(newFolder):
showWarning(_("Folder already exists."))
self.name = oldName
return
# update name
self.db.execute("update profiles set name = ? where name = ?",
name.encode("utf8"), oldName.encode("utf-8"))
# rename folder
os.rename(oldFolder, newFolder)
self.db.commit()
# Folder handling
######################################################################
def profileFolder(self, create=True):
#.........这里部分代码省略.........
示例2: MediaManager
# 需要导入模块: from anki.db import DB [as 别名]
# 或者: from anki.db.DB import commit [as 别名]
#.........这里部分代码省略.........
def copyTo(self, rdir):
"Copy media to RDIR. Return number of files copied."
ldir = self.dir()
if not os.path.exists(ldir):
return 0
cnt = 0
for f in os.listdir(ldir):
src = os.path.join(ldir, f)
dst = os.path.join(rdir, f)
if not os.path.exists(dst):
shutil.copy2(src, dst)
cnt += 1
return cnt
# Media syncing - changes and removal
##########################################################################
def hasChanged(self):
return self.db.scalar("select 1 from log limit 1")
def removed(self):
return self.db.list("select * from log where type = ?", MEDIA_REM)
def syncRemove(self, fnames):
# remove provided deletions
for f in fnames:
if os.path.exists(f):
os.unlink(f)
self.db.execute("delete from log where fname = ?", f)
self.db.execute("delete from media where fname = ?", f)
# and all locally-logged deletions, as server has acked them
self.db.execute("delete from log where type = ?", MEDIA_REM)
self.db.commit()
# Media syncing - unbundling zip files from server
##########################################################################
def syncAdd(self, zipData):
"Extract zip data; true if finished."
f = StringIO(zipData)
z = zipfile.ZipFile(f, "r")
finished = False
meta = None
media = []
sizecnt = 0
# get meta info first
assert z.getinfo("_meta").file_size < 100000
meta = simplejson.loads(z.read("_meta"))
nextUsn = int(z.read("_usn"))
# then loop through all files
for i in z.infolist():
# check for zip bombs
sizecnt += i.file_size
assert sizecnt < 100*1024*1024
if i.filename == "_meta" or i.filename == "_usn":
# ignore previously-retrieved meta
continue
elif i.filename == "_finished":
# last zip in set
finished = True
else:
data = z.read(i)
csum = checksum(data)
name = meta[i.filename]
# can we store the file on this system?
示例3: ProfileManager
# 需要导入模块: from anki.db import DB [as 别名]
# 或者: from anki.db.DB import commit [as 别名]
class ProfileManager(object):
def __init__(self, base=None, profile=None):
self.name = None
# instantiate base folder
if not base:
base = self._defaultBase()
self.ensureBaseExists(base)
self.checkPid(base)
self.base = base
# load database and cmdline-provided profile
self._load()
if profile:
try:
self.load(profile)
except TypeError:
raise Exception("Provided profile does not exist.")
# Startup checks
######################################################################
# These routines run before the language code is initialized, so they
# can't be translated
def ensureBaseExists(self, base):
if not os.path.exists(base):
try:
os.makedirs(base)
except:
QMessageBox.critical(
None, "Error", """\
Anki can't write to the harddisk. Please see the \
documentation for information on using a flash drive.""")
raise
def checkPid(self, base):
p = os.path.join(base, "pid")
# check if an existing instance is running
if os.path.exists(p):
pid = int(open(p).read())
exists = False
try:
os.kill(pid, 0)
exists = True
except OSError:
pass
if exists:
QMessageBox.warning(
None, "Error", """\
Anki is already running. Please close the existing copy or restart your \
computer.""")
raise Exception("Already running")
# write out pid to the file
open(p, "w").write(str(os.getpid()))
# add handler to cleanup on exit
def cleanup():
os.unlink(p)
atexit.register(cleanup)
# Profile load/save
######################################################################
def profiles(self):
return sorted(
x for x in self.db.list("select name from profiles")
if x != "_global")
def load(self, name, passwd=None):
prof = cPickle.loads(
self.db.scalar("select data from profiles where name = ?", name))
if prof['key'] and prof['key'] != self._pwhash(passwd):
self.name = None
return False
if name != "_global":
self.name = name
self.profile = prof
return True
def save(self):
sql = "update profiles set data = ? where name = ?"
self.db.execute(sql, cPickle.dumps(self.profile), self.name)
self.db.execute(sql, cPickle.dumps(self.meta), "_global")
self.db.commit()
def create(self, name):
prof = profileConf.copy()
prof['lang'] = self.meta['defaultLang']
self.db.execute("insert into profiles values (?, ?)",
name, cPickle.dumps(prof))
self.db.commit()
def remove(self, name):
shutil.rmtree(self.profileFolder())
self.db.execute("delete from profiles where name = ?", name)
self.db.commit()
def rename(self, name):
oldFolder = self.profileFolder()
# update name
self.db.execute("update profiles set name = ? where name = ?",
name, self.name)
#.........这里部分代码省略.........
示例4: __init__
# 需要导入模块: from anki.db import DB [as 别名]
# 或者: from anki.db.DB import commit [as 别名]
class ProfileManager:
def __init__(self, base=None, profile=None):
self.name = None
self.db = None
# instantiate base folder
self._setBaseFolder(base)
# load metadata
self.firstRun = self._loadMeta()
# did the user request a profile to start up with?
if profile:
if profile not in self.profiles():
QMessageBox.critical(None, "Error", "Requested profile does not exist.")
sys.exit(1)
try:
self.load(profile)
except TypeError:
raise Exception("Provided profile does not exist.")
# Base creation
######################################################################
def ensureBaseExists(self):
try:
self._ensureExists(self.base)
except:
# can't translate, as lang not initialized
QMessageBox.critical(
None, "Error", """\
Anki could not create the folder %s. Please ensure that location is not \
read-only and you have permission to write to it. If you cannot fix this \
issue, please see the documentation for information on running Anki from \
a flash drive.""" % self.base)
raise
# Folder migration
######################################################################
def _oldFolderLocation(self):
if isMac:
return os.path.expanduser("~/Documents/Anki")
elif isWin:
loc = QStandardPaths.writableLocation(QStandardPaths.DocumentsLocation)
return os.path.join(loc, "Anki")
else:
p = os.path.expanduser("~/Anki")
if os.path.exists(p):
return p
else:
loc = QStandardPaths.writableLocation(QStandardPaths.DocumentsLocation)
if loc[:-1] == QStandardPaths.writableLocation(
QStandardPaths.HomeLocation):
# occasionally "documentsLocation" will return the home
# folder because the Documents folder isn't configured
# properly; fall back to an English path
return os.path.expanduser("~/Documents/Anki")
else:
return os.path.join(loc, "Anki")
def maybeMigrateFolder(self):
oldBase = self._oldFolderLocation()
if not os.path.exists(self.base) and os.path.exists(oldBase):
shutil.move(oldBase, self.base)
# Profile load/save
######################################################################
def profiles(self):
return sorted(x for x in
self.db.list("select name from profiles")
if x != "_global")
def load(self, name, passwd=None):
data = self.db.scalar("select cast(data as blob) from profiles where name = ?", name)
# some profiles created in python2 may not decode properly
prof = pickle.loads(data, errors="ignore")
if prof['key'] and prof['key'] != self._pwhash(passwd):
self.name = None
return False
if name != "_global":
self.name = name
self.profile = prof
return True
def save(self):
sql = "update profiles set data = ? where name = ?"
self.db.execute(sql, pickle.dumps(self.profile), self.name)
self.db.execute(sql, pickle.dumps(self.meta), "_global")
self.db.commit()
def create(self, name):
prof = profileConf.copy()
self.db.execute("insert into profiles values (?, ?)",
name, pickle.dumps(prof))
self.db.commit()
def remove(self, name):
p = self.profileFolder()
if os.path.exists(p):
#.........这里部分代码省略.........
示例5: MediaManager
# 需要导入模块: from anki.db import DB [as 别名]
# 或者: from anki.db.DB import commit [as 别名]
class MediaManager(object):
soundRegexps = ["(?i)(\[sound:(?P<fname>[^]]+)\])"]
imgRegexps = [
# src element quoted case
"(?i)(<img[^>]* src=(?P<str>[\"'])(?P<fname>[^>]+?)(?P=str)[^>]*>)",
# unquoted case
"(?i)(<img[^>]* src=(?!['\"])(?P<fname>[^ >]+)[^>]*?>)",
]
regexps = soundRegexps + imgRegexps
def __init__(self, col, server):
self.col = col
if server:
self._dir = None
return
# media directory
self._dir = re.sub("(?i)\.(anki2)$", ".media", self.col.path)
# convert dir to unicode if it's not already
if isinstance(self._dir, str):
self._dir = unicode(self._dir, sys.getfilesystemencoding())
if not os.path.exists(self._dir):
os.makedirs(self._dir)
try:
self._oldcwd = os.getcwd()
except OSError:
# cwd doesn't exist
self._oldcwd = None
try:
os.chdir(self._dir)
except OSError:
raise Exception("invalidTempFolder")
# change database
self.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()
def _initDB(self):
self.db.executescript("""
create table media (
fname text not null primary key,
csum text, -- null indicates deleted file
mtime int not null, -- zero if deleted
dirty int not null
);
create index idx_media_dirty on media (dirty);
create table meta (dirMod int, lastUsn int); insert into meta values (0, 0);
""")
def maybeUpgrade(self):
oldpath = self.dir()+".db"
if os.path.exists(oldpath):
self.db.execute('attach "../collection.media.db" as old')
try:
self.db.execute("""
insert into media
select m.fname, csum, mod, ifnull((select 1 from log l2 where l2.fname=m.fname), 0) as dirty
from old.media m
left outer join old.log l using (fname)
union
select fname, null, 0, 1 from old.log where type=1;""")
self.db.execute("delete from meta")
self.db.execute("""
insert into meta select dirMod, usn from old.meta
""")
self.db.commit()
except Exception, e:
# if we couldn't import the old db for some reason, just start
# anew
self.col.log("failed to import old media db:"+traceback.format_exc())
self.db.execute("detach old")
npath = "../collection.media.db.old"
if os.path.exists(npath):
os.unlink(npath)
os.rename("../collection.media.db", npath)
示例6: MediaManager
# 需要导入模块: from anki.db import DB [as 别名]
# 或者: from anki.db.DB import commit [as 别名]
#.........这里部分代码省略.........
def allMedia(self):
"Return a set of all referenced filenames."
files = set()
for mid, flds in self.col.db.execute("select mid, flds from notes"):
for f in self.filesInStr(mid, flds):
files.add(f)
return files
# Copying on import
##########################################################################
def have(self, fname):
return os.path.exists(os.path.join(self.dir(), fname))
# Media syncing - changes and removal
##########################################################################
def hasChanged(self):
return self.db.scalar("select 1 from log limit 1")
def removed(self):
return self.db.list("select * from log where type = ?", MEDIA_REM)
def syncRemove(self, fnames):
# remove provided deletions
for f in fnames:
if os.path.exists(f):
send2trash.send2trash(f)
self.db.execute("delete from log where fname = ?", f)
self.db.execute("delete from media where fname = ?", f)
# and all locally-logged deletions, as server has acked them
self.db.execute("delete from log where type = ?", MEDIA_REM)
self.db.commit()
# Media syncing - unbundling zip files from server
##########################################################################
def syncAdd(self, zipData):
"Extract zip data; true if finished."
f = StringIO(zipData)
z = zipfile.ZipFile(f, "r")
finished = False
meta = None
media = []
sizecnt = 0
# get meta info first
assert z.getinfo("_meta").file_size < 100000
meta = json.loads(z.read("_meta"))
nextUsn = int(z.read("_usn"))
# then loop through all files
for i in z.infolist():
# check for zip bombs
sizecnt += i.file_size
assert sizecnt < 100*1024*1024
if i.filename == "_meta" or i.filename == "_usn":
# ignore previously-retrieved meta
continue
elif i.filename == "_finished":
# last zip in set
finished = True
else:
data = z.read(i)
csum = checksum(data)
name = meta[i.filename]
# can we store the file on this system?
示例7: __init__
# 需要导入模块: from anki.db import DB [as 别名]
# 或者: from anki.db.DB import commit [as 别名]
class MediaManager:
soundRegexps = ["(?i)(\[sound:(?P<fname>[^]]+)\])"]
imgRegexps = [
# src element quoted case
"(?i)(<img[^>]* src=(?P<str>[\"'])(?P<fname>[^>]+?)(?P=str)[^>]*>)",
# unquoted case
"(?i)(<img[^>]* src=(?!['\"])(?P<fname>[^ >]+)[^>]*?>)",
]
regexps = soundRegexps + imgRegexps
def __init__(self, col, server):
self.col = col
if server:
self._dir = None
return
# media directory
self._dir = re.sub("(?i)\.(anki2)$", ".media", self.col.path)
if not os.path.exists(self._dir):
os.makedirs(self._dir)
# change database
self.connect()
def connect(self):
if self.col.server:
return
path = self.dir()+".db2"
create = not os.path.exists(path)
self.db = DB(path)
if create:
self._initDB()
self.maybeUpgrade()
def _initDB(self):
self.db.executescript("""
create table media (
fname text not null primary key,
csum text, -- null indicates deleted file
mtime int not null, -- zero if deleted
dirty int not null
);
create index idx_media_dirty on media (dirty);
create table meta (dirMod int, lastUsn int); insert into meta values (0, 0);
""")
def maybeUpgrade(self):
oldpath = self.dir()+".db"
if os.path.exists(oldpath):
self.db.execute('attach "../collection.media.db" as old')
try:
self.db.execute("""
insert into media
select m.fname, csum, mod, ifnull((select 1 from log l2 where l2.fname=m.fname), 0) as dirty
from old.media m
left outer join old.log l using (fname)
union
select fname, null, 0, 1 from old.log where type=1;""")
self.db.execute("delete from meta")
self.db.execute("""
insert into meta select dirMod, usn from old.meta
""")
self.db.commit()
except Exception as e:
# if we couldn't import the old db for some reason, just start
# anew
self.col.log("failed to import old media db:"+traceback.format_exc())
self.db.execute("detach old")
npath = os.path.join(self.dir(), "collection.media.db.old")
if os.path.exists(npath):
os.unlink(npath)
os.rename(os.path.join(self.dir(), "collection.media.db"), npath)
def close(self):
if self.col.server:
return
self.db.close()
self.db = None
def dir(self):
return self._dir
def _isFAT32(self):
if not isWin:
return
import win32api, win32file
try:
name = win32file.GetVolumeNameForVolumeMountPoint(self._dir[:3])
except:
# mapped & unmapped network drive; pray that it's not vfat
return
if win32api.GetVolumeInformation(name)[4].lower().startswith("fat"):
return True
# Adding media
##########################################################################
# opath must be in unicode
def addFile(self, opath):
#.........这里部分代码省略.........
示例8: __init__
# 需要导入模块: from anki.db import DB [as 别名]
# 或者: from anki.db.DB import commit [as 别名]
#.........这里部分代码省略.........
def find_class(self, module, name):
fn = super().find_class(module, name)
if module == "sip" and name == "_unpickle_type":
def wrapper(mod, obj, args):
if mod.startswith("PyQt4") and obj == "QByteArray":
# can't trust str objects from python 2
return QByteArray()
return fn(mod, obj, args)
return wrapper
else:
return fn
up = Unpickler(io.BytesIO(data), errors="ignore")
return up.load()
def _pickle(self, obj):
return pickle.dumps(obj, protocol=0)
def load(self, name):
assert name != "_global"
data = self.db.scalar("select cast(data as blob) from profiles where name = ?", name)
self.name = name
try:
self.profile = self._unpickle(data)
except:
print("resetting corrupt profile")
self.profile = profileConf.copy()
self.save()
return True
def save(self):
sql = "update profiles set data = ? where name = ?"
self.db.execute(sql, self._pickle(self.profile), self.name)
self.db.execute(sql, self._pickle(self.meta), "_global")
self.db.commit()
def create(self, name):
prof = profileConf.copy()
self.db.execute("insert or ignore into profiles values (?, ?)",
name, self._pickle(prof))
self.db.commit()
def remove(self, name):
p = self.profileFolder()
if os.path.exists(p):
send2trash(p)
self.db.execute("delete from profiles where name = ?", name)
self.db.commit()
def trashCollection(self):
p = self.collectionPath()
if os.path.exists(p):
send2trash(p)
def rename(self, name):
oldName = self.name
oldFolder = self.profileFolder()
self.name = name
newFolder = self.profileFolder(create=False)
if os.path.exists(newFolder):
if (oldFolder != newFolder) and (
oldFolder.lower() == newFolder.lower()):
# OS is telling us the folder exists because it does not take
# case into account; use a temporary folder location
midFolder = ''.join([oldFolder, '-temp'])
if not os.path.exists(midFolder):
os.rename(oldFolder, midFolder)
示例9: ProfileManager
# 需要导入模块: from anki.db import DB [as 别名]
# 或者: from anki.db.DB import commit [as 别名]
class ProfileManager(object):
def __init__(self, base=None, profile=None):
self.name = None
# instantiate base folder
if base:
self.base = os.path.abspath(base)
else:
self.base = self._defaultBase()
self.ensureBaseExists()
# load metadata
self.firstRun = self._loadMeta()
# did the user request a profile to start up with?
if profile:
try:
self.load(profile)
except TypeError:
raise Exception("Provided profile does not exist.")
# Base creation
######################################################################
def ensureBaseExists(self):
try:
self._ensureExists(self.base)
except:
# can't translate, as lang not initialized
QMessageBox.critical(
None, "Error", """\
Anki can't write to the harddisk. Please see the \
documentation for information on using a flash drive.""")
raise
# Profile load/save
######################################################################
def profiles(self):
return sorted(
unicode(x, "utf8") for x in
self.db.list("select name from profiles")
if x != "_global")
def load(self, name, passwd=None):
prof = cPickle.loads(
self.db.scalar("select data from profiles where name = ?",
name.encode("utf8")))
if prof['key'] and prof['key'] != self._pwhash(passwd):
self.name = None
return False
if name != "_global":
self.name = name
self.profile = prof
return True
def save(self):
sql = "update profiles set data = ? where name = ?"
self.db.execute(sql, cPickle.dumps(self.profile),
self.name.encode("utf8"))
self.db.execute(sql, cPickle.dumps(self.meta), "_global")
self.db.commit()
def create(self, name):
prof = profileConf.copy()
self.db.execute("insert into profiles values (?, ?)",
name.encode("utf8"), cPickle.dumps(prof))
self.db.commit()
def remove(self, name):
p = self.profileFolder()
if os.path.exists(p):
send2trash(p)
self.db.execute("delete from profiles where name = ?",
name.encode("utf8"))
self.db.commit()
def rename(self, name):
oldName = self.name
oldFolder = self.profileFolder()
self.name = name
newFolder = self.profileFolder(create=False)
if os.path.exists(newFolder):
showWarning(_("Folder already exists."))
self.name = oldName
return
# update name
self.db.execute("update profiles set name = ? where name = ?",
name.encode("utf8"), oldName.encode("utf-8"))
# rename folder
os.rename(oldFolder, newFolder)
self.db.commit()
# Folder handling
######################################################################
def profileFolder(self, create=True):
path = os.path.join(self.base, self.name)
if create:
self._ensureExists(path)
return path
#.........这里部分代码省略.........