本文整理汇总了Python中peewee.SqliteDatabase类的典型用法代码示例。如果您正苦于以下问题:Python SqliteDatabase类的具体用法?Python SqliteDatabase怎么用?Python SqliteDatabase使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SqliteDatabase类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: wrapper
def wrapper(*args, **kwargs):
language = kwargs.get("language", "en")
path = kwargs.pop("database_path", None)
if not path:
path = CONTENT_DATABASE_PATH.format(
channel=kwargs.get("channel", CHANNEL),
language=language
)
db = SqliteDatabase(path, pragmas=settings.CONTENT_DB_SQLITE_PRAGMAS)
kwargs["db"] = db
db.connect()
# This should contain all models in the database to make them available to the wrapped function
with Using(db, [Item, AssessmentItem]):
try:
output = function(*args, **kwargs)
except DoesNotExist:
output = None
except OperationalError:
logging.error("No content database file found")
raise
db.close()
return output
示例2: create_relations
def create_relations():
# запоминаем все используемые в бд модели
models = [User, RunSettings]
# чистим базу данных
print('чистим базу данных')
db = SqliteDatabase('data.db')
try:
db.drop_tables(models)
except OperationalError:
pass
# создаем таблицы в бд
print('\nсоздаем модели в бд:')
for i in models:
print(i)
i.create_table()
# добавляем пользователя
print('\nдобавляем пользователя')
admin_user = User(mail="[email protected]", password=get_hash('1'), port=56001)
admin_user.save()
test_user = User(mail="[email protected]", password=get_hash('1'), port=9701)
test_user.save()
示例3: DBProxy
class PWDatabase:
__proxy = None
@staticmethod
def DBProxy():
if not PWDatabase.__proxy:
PWDatabase.__proxy = Proxy()
return PWDatabase.__proxy
_db = None
def __init__(self, path):
try:
self._db = SqliteDatabase(path, check_same_thread=False)
PWDatabase.DBProxy().initialize(self._db)
self.startup()
except Exception as e:
logger.error("database file does not exist, or incorrect permissions")
def close(self):
self._db.close()
self._db = None
def startup(self):
self._db.connect()
@property
def DB(self):
return self._db
示例4: init
def init(dbname="blender-models.db"):
db = SqliteDatabase(path.join(MORSEWEB_ROOT, dbname))
db.connect()
if not BlenderModel.table_exists():
db.create_table(BlenderModel)
for pathname in RESOURCES:
populate(pathname)
示例5: OnInit
def OnInit(self):
wx.InitAllImageHandlers()
F = wx.SplashScreen(
wx.Bitmap("../icons/splash.bmp"), wx.SPLASH_TIMEOUT | wx.SPLASH_CENTER_ON_SCREEN, 2000, None, -1
)
frame_EcranPrincipal = MainFrame(None, title=u"Usine à GASE", droits=1)
self.SetTopWindow(frame_EcranPrincipal)
frame_EcranPrincipal.Show()
try:
database = SqliteDatabase("usineagase.sqlite", **{})
tables_base = database.get_tables()
except:
msg = u"Erreur de connection à la base de données"
dlg = wx.MessageDialog(None, msg, "ERREUR", wx.OK | wx.ICON_EXCLAMATION)
dlg.ShowModal()
dlg.Destroy()
return 0
tables_obligatoires = [
u"achats",
u"adherents",
u"adhesion_types",
u"adhesions",
u"cotisations",
u"categories",
u"credits",
u"commandes",
u"exercices",
u"fournisseurs",
u"lignes_achat",
u"lignes_commande",
u"parametres",
u"produits",
u"referents",
u"tvas",
]
if set(tables_obligatoires) - set(tables_base):
msg = u"Erreur : la base de données n'est pas accessible ou n'est pas conforme."
dlg = wx.MessageDialog(None, msg, "ERREUR", wx.OK | wx.ICON_EXCLAMATION)
dlg.ShowModal()
dlg.Destroy()
return 0
else:
# query = session.query(model.Exercice).filter(model.Exercice.DateDebut<datetime.today()).filter(model.Exercice.DateFin>datetime.today())
# Exercice.select().where(date_debut<datetime.today())
# if query.count() == 1:
# EXERCICE_EN_COURS = query.first()
return 1
示例6: bundle_language_pack
def bundle_language_pack(dest, nodes, frontend_catalog, backend_catalog, metadata, assessment_items, assessment_files, subtitles, html_exercise_path):
# make sure dest's parent directories exist
pathlib.Path(dest).parent.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(dest, "w") as zf, tempfile.NamedTemporaryFile() as dbf:
db = SqliteDatabase(dbf.name)
db.connect()
nodes = convert_dicts_to_models(nodes)
nodes = mark_exercises_as_available(nodes)
nodes = list(save_models(nodes, db)) # we have to make sure to force
# the evaluation of each
# save_models call, in order to
# avoid nesting them.
nodes = list(populate_parent_foreign_keys(nodes))
list(save_models(nodes, db))
nodes = recurse_availability_up_tree(nodes, db)
list(save_models(nodes, db))
assessment_items = convert_dicts_to_assessment_items(assessment_items)
list(save_assessment_items(assessment_items, db))
db.close()
dbf.flush()
save_catalog(frontend_catalog, zf, "frontend.mo")
save_catalog(backend_catalog, zf, "backend.mo")
# save_subtitles(subtitle_path, zf)
try: # sometimes we have no html exercises
save_html_exercises(html_exercise_path, zf)
except FileNotFoundError:
logging.warning("No html exercises found; skipping.")
save_db(db, zf)
save_metadata(zf, metadata)
for file_path in assessment_files:
save_assessment_file(file_path, zf)
write_assessment_version(metadata, zf)
for subtitle_path in subtitles:
save_subtitle(subtitle_path, zf)
return dest
示例7: __init__
def __init__(self, path):
try:
self._db = SqliteDatabase(path, check_same_thread=False)
PWDatabase.DBProxy().initialize(self._db)
self.startup()
except Exception as e:
logger.error("database file does not exist, or incorrect permissions")
示例8: test_database_generation_without_args
def test_database_generation_without_args(runner, tmp_context):
result = runner.invoke(pokediadb, ["generate", "-v"])
assert result.exit_code == 0
# Check existence of the database and the csv and sprites folders
db_file = tmp_context.join("pokediadb.sql")
assert db_file.check(file=1)
assert tmp_context.join("csv").check(dir=1)
assert tmp_context.join("sprites").check(dir=1)
# Check type tables
db = SqliteDatabase(db_file.strpath)
db.connect()
assert len(Type.select()) == 18
assert len(TypeEfficacy.select()) == 324
assert len(TypeTranslation.select()) == 36
示例9: setUp
def setUp(self):
self.db = SqliteDatabase('peewee.db')
self.db.connect()
self.db.create_tables([Device, Group, User, UserToGroup, Publication], safe=True)
Device.delete().execute()
Group.delete().execute()
User.delete().execute()
UserToGroup.delete().execute()
Publication.delete().execute()
self.user0 = User.create_user(name='user0name', username='user0username', password='user0password')
self.user0.create_device(name='device0name', resource='device0resource', type='device0type', dev_id='device0id', reg_id='device0regid')
self.user1 = User.create_user(name='user1name', username='user1username', password='user1password')
self.user1.create_device(name='device1name', resource='device1resource', type='device1type', dev_id='device1id')
self.group0 = Group.create(name='group0name', description='group0description', owner=self.user0)
self.group0.add_user(user=self.user0)
self.group0.add_user(user=self.user1)
self.group1 = Group.create(name='group1name', description='group1description', owner=self.user0)
self.group1.add_user(user=self.user0)
self.group2 = Group.create(name='group2name', description='group2description', owner=self.user1)
self.group2.add_user(user=self.user1)
self.pub0 = Publication.create(user=self.user0, topic='pub0topic', description='pub0description', publish_group=self.group1, subscribe_group=self.group0)
示例10: populate_database
def populate_database(self):
self.db = SqliteDatabase('peewee.db')
self.db.connect()
self.db.create_tables(model.ALL_MODELS, safe=True)
for m in model.ALL_MODELS:
m.delete().execute()
self.db.close()
# Config
release = model.Config.create(app_api_key=APP_API_KEY, messaging_api_key=MESSAGING_API_KEY)
admin_user = model.User.create_user(name='Administrator', description='Administrator', email='[email protected]', username=TEST_USER, password=TEST_PASSWORD)
# Groups
admin = model.Group.create(name=TEST_USER, owner=admin_user)
user = model.Group.create(name='user', owner=admin_user)
guest = model.Group.create(name='guest', owner=admin_user)
admin.add_user(admin_user)
# Users
model.Device.create(user=admin, name='d2', resource='work', type='computer', dev_id='a')
chloe = model.User.create_user(name='Chloe', username='chloe', password=TEST_PASSWORD)
d = chloe.create_device(name='d2', resource='work', type='computer', dev_id='a')
chloe.create_device(name='d0', resource='home', type='phone', dev_id='b')
chloe.create_device(name='d3', resource='home', type='laptop', dev_id='c')
chloe.create_device(name='d1', resource='work', type='phone', dev_id='d')
model.UserToGroup.create(user=chloe, group=guest)
sunshine = model.User.create_user(name='Sunshine', username='sunshine', password=TEST_PASSWORD)
sunshine.create_device(name='d5', resource='work', type='phone', dev_id='e')
model.UserToGroup.create(user=sunshine, group=user)
model.UserToGroup.create(user=sunshine, group=guest)
p = model.Publication.create(user=sunshine, topic='Life and Times of Sunshine', description='', publish_group=guest, subscribe_group=guest)
model.Message.create(user=sunshine, to_publication=p, subject='First post!')
model.Message.create(user=sunshine, to_publication=p, subject='Eating breakfast')
model.Message.create(user=sunshine, to_publication=p, subject='Time for a nap')
guinness = model.User.create_user(name='Guinness', username='guinness', password=TEST_PASSWORD)
guinness.create_device(name='d7', resource='work', type='phone', dev_id='g')
model.UserToGroup.create(user=guinness, group=guest)
felix = model.User.create_user(name='Felix', username='felix', password=TEST_PASSWORD)
felix.create_device(name='d6', resource='work', type='phone', dev_id='f')
model.UserToGroup.create(user=felix, group=guest)
model.Subscription.create(user=felix, publication=p)
model.Message.create(user=felix, to_publication=p, subject='boring...')
model.Message.create(user=felix, to_user=sunshine, subject='hi sunshine')
model.Message.create(user=felix, to_device=d, subject='hi chloe')
model.Message.create(user=felix, to_user=chloe, subject='hi chloe again')
ducky = model.User.create_user(name='Ducky', username='ducky', password=TEST_PASSWORD)
ducky.create_device(name='d8', resource='work', type='phone', dev_id='h')
model.UserToGroup.create(user=ducky, group=admin)
model.UserToGroup.create(user=ducky, group=user)
model.UserToGroup.create(user=ducky, group=guest)
示例11: init
def init():
path = os.path.expanduser('~/.config/aesop/database.db')
global database
database = SqliteDatabase(path)
database_proxy.initialize(database)
database.connect()
for model in BaseModel.__subclasses__():
try:
database.create_table(model)
except Exception:
pass
else:
if model == Config:
Config.create_default()
示例12: build_features_tree
def build_features_tree(self):
from peewee import SqliteDatabase, Model, IntegerField, CharField, BooleanField
# built or connect database
sqlite_path = {
"memory" : ":memory:",
"disk" : self.sqlite3db_path(),
}[self.link_to_detdup.storage_type]
sqlite_database = SqliteDatabase(sqlite_path, check_same_thread=False)
class BaseFeaturesTree(Model):
uniq_chars__len = IntegerField(default=0)
sqrt_chars__len = IntegerField(default=0)
sorted_freq_chars = CharField()
# TODO support item_id as int or str type
item_id = CharField()
class Meta:
database = sqlite_database
self.features_tree = BaseFeaturesTree
tablename = "_".join(self.custom_features).capitalize() or "DefaultFeaturesTree"
# If customize more features
if self.custom_features:
self.features_tree = type(tablename, (BaseFeaturesTree,), dict())
for feature_k1 in self.custom_features:
# http://stackoverflow.com/questions/22358489/dynamically-define-fields-in-a-peewee-model
feature_v1 = self.custom_features[feature_k1]
# Compact with (int) instance
if type(feature_v1) is int: feature_v1 = int
field1 = {int: IntegerField, str: CharField}[feature_v1]()
field1.add_to_class(self.features_tree, feature_k1)
self.features_tree._meta.db_table = tablename
# create table and indexes
if not self.features_tree.table_exists():
self.features_tree.create_table()
sqlite_database.create_index(self.features_tree, "item_id".split(" "))
# TODO 让大str在前面,加快索引搜索速度
index_columns = self.default_features.keys() + self.custom_features.keys()
sqlite_database.create_index(self.features_tree, index_columns)
print "[build_features_tree]", self.features_tree, "self.default_features :", self.default_features, "self.custom_features :", self.custom_features
print
示例13: crapTheData
def crapTheData(config):
db = SqliteDatabase(config['database_name']+'.db')
db.connect()
for name,url in config['urls'].iteritems():
print name, 'craping '+url
maxnum = generateTable(url, config['params'][name], name, db)
print 'we need to crap',maxnum,' rows data'
# db.create_tables([Table],safe=True)
datalist = []
for i in range(maxnum):
params = config['params'][name]
params['page'] = i
res = requests.get(url, params ,headers=headers)
print i, len(datalist)
data = res.json().get('tngou')
if data:
datalist.append(data[0])
storeData(config['database_name']+name+'.pic', datalist)
示例14: __init__
def __init__(self, db):
""" Initialize the manager for agent locations and outpost resource
storage.
db - absolute path to database file (sqlite)
"""
self.db = SqliteDatabase(db)
zone_book_proxy.initialize(self.db)
self.db.create_tables([OutpostZone, AgentZone], True)
示例15: _get_db
def _get_db(self):
"""
Get a database connection, initialize it if not done so yet
:return: SqliteDatabase instance
"""
if not self.db:
self.db = SqliteDatabase(self.settings.DATABASE_PATH)
self.db.connect()
return self.db