本文整理汇总了Python中peewee.SqliteDatabase.connect方法的典型用法代码示例。如果您正苦于以下问题:Python SqliteDatabase.connect方法的具体用法?Python SqliteDatabase.connect怎么用?Python SqliteDatabase.connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类peewee.SqliteDatabase
的用法示例。
在下文中一共展示了SqliteDatabase.connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: DBProxy
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import connect [as 别名]
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
示例2: wrapper
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import connect [as 别名]
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
示例3: test_writes_db_to_archive
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import connect [as 别名]
def test_writes_db_to_archive(self):
with tempfile.NamedTemporaryFile() as zffobj:
zf = zipfile.ZipFile(zffobj, "w")
with tempfile.NamedTemporaryFile() as dbfobj:
db = SqliteDatabase(dbfobj.name)
db.connect()
with Using(db, [Item]):
Item.create_table()
item = Item(id="test", title="test",
description="test", available=False,
slug="srug", kind=NodeType.video,
path="/test/test")
item.save()
db.close()
save_db(db, zf)
zf.close()
# reopen the db from the zip, see if our object was saved
with tempfile.NamedTemporaryFile() as f:
# we should only have one file in the zipfile, the db. Assume
# that the first file is the db.
zf = zipfile.ZipFile(zffobj.name)
dbfobj = zf.open(zf.infolist()[0])
f.write(dbfobj.read())
f.seek(0)
db = SqliteDatabase(f.name)
with Using(db, [Item]):
Item.get(title="test")
示例4: init
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import connect [as 别名]
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: TestManage
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import connect [as 别名]
class TestManage(unittest.TestCase):
def setUp(self):
self.db = SqliteDatabase('peewee.db')
self.db.connect()
def tearDown(self):
self.db.close()
def testCreate(self):
self.db.create_tables(ALL_MODELS, safe=True)
示例6: init_models
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import connect [as 别名]
def init_models(app):
if app.config['TESTING']:
database = SqliteDatabase(':memory:')
else:
database = SqliteDatabase('local.db')
database_proxy.initialize(database)
database.connect()
database.create_tables([
TodoItem,
], safe=True)
示例7: bundle_language_pack
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import connect [as 别名]
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
示例8: test_database_generation_without_args
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import connect [as 别名]
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: init
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import connect [as 别名]
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()
示例10: crapTheData
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import connect [as 别名]
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)
示例11: empty
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import connect [as 别名]
def empty(self, *args, **options):
"""
Creates an empty content database for the Khan channel. This ensures
that an empty content database exists in the default distribution and
for tests.
Especially useful for creating an *EMPTY TEMPLATE*
retrievecontentpack empty en --template
"""
lang = args[1]
if not options.get('template', False):
content_db_path = topic_settings.CONTENT_DATABASE_PATH.format(
channel=topic_settings.CHANNEL,
language=lang,
)
else:
content_db_path = topic_settings.CONTENT_DATABASE_TEMPLATE_PATH.format(
channel=topic_settings.CHANNEL,
language=lang,
)
if os.path.exists(content_db_path):
if options.get("force", False):
os.unlink(content_db_path)
else:
raise CommandError(
"Content database already exists: {}".format(
content_db_path
)
)
db = SqliteDatabase(
content_db_path
)
db.connect()
db.create_table(Item, safe=True)
db.create_table(AssessmentItem, safe=True)
db.close()
self.complete(
_("Saved empty content database in {}.").format(
content_db_path
)
)
示例12: bundle_language_pack
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import connect [as 别名]
def bundle_language_pack(dest, nodes, frontend_catalog, backend_catalog, metadata, assessment_items, assessment_files, subtitles):
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)
save_db(db, zf)
save_metadata(zf, metadata)
for file_path in assessment_files:
save_assessment_file(file_path, zf)
for subtitle_path in subtitles:
save_subtitle(subtitle_path, zf)
return dest
示例13: test_deferred_database
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import connect [as 别名]
def test_deferred_database(self):
deferred_db = SqliteDatabase(None)
self.assertTrue(deferred_db.deferred)
class DeferredModel(Model):
class Meta:
database = deferred_db
self.assertRaises(Exception, deferred_db.connect)
sq = DeferredModel.select()
self.assertRaises(Exception, sq.execute)
deferred_db.init(':memory:')
self.assertFalse(deferred_db.deferred)
# connecting works
conn = deferred_db.connect()
DeferredModel.create_table()
sq = DeferredModel.select()
self.assertEqual(list(sq), [])
deferred_db.init(None)
self.assertTrue(deferred_db.deferred)
示例14: SqliteDatabase
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import connect [as 别名]
from playhouse.migrate import SqliteMigrator
from playhouse.migrate import migrate as run_migrate
from tmc.errors import NoCourseSelected, NoExerciseSelected
target_file = os.environ.get("TMC_DATABASEFILE",
os.path.join(os.path.expanduser("~"),
".config",
"tmc.db"))
# SqliteDatabase will fail if the parent directory isn't there.
if not os.path.isdir(os.path.dirname(target_file)):
os.mkdir(os.path.dirname(target_file), 0o700)
sqlite = SqliteDatabase(target_file)
sqlite.connect()
class BaseModel(Model):
class Meta:
database = sqlite
class SchemaVersion(BaseModel):
version = IntegerField()
class Course(BaseModel):
tid = IntegerField(unique=True)
name = CharField()
示例15:
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import connect [as 别名]
ask_volume_1=self.ask_volume_1,
gateway_name=self.gateway_name,
)
if self.bid_price_2:
tick.bid_price_2 = self.bid_price_2
tick.bid_price_3 = self.bid_price_3
tick.bid_price_4 = self.bid_price_4
tick.bid_price_5 = self.bid_price_5
tick.ask_price_2 = self.ask_price_2
tick.ask_price_3 = self.ask_price_3
tick.ask_price_4 = self.ask_price_4
tick.ask_price_5 = self.ask_price_5
tick.bid_volume_2 = self.bid_volume_2
tick.bid_volume_3 = self.bid_volume_3
tick.bid_volume_4 = self.bid_volume_4
tick.bid_volume_5 = self.bid_volume_5
tick.ask_volume_2 = self.ask_volume_2
tick.ask_volume_3 = self.ask_volume_3
tick.ask_volume_4 = self.ask_volume_4
tick.ask_volume_5 = self.ask_volume_5
return tick
DB.connect()
DB.create_tables([DbBarData, DbTickData])