本文整理汇总了Python中peewee.SqliteDatabase.close方法的典型用法代码示例。如果您正苦于以下问题:Python SqliteDatabase.close方法的具体用法?Python SqliteDatabase.close怎么用?Python SqliteDatabase.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类peewee.SqliteDatabase
的用法示例。
在下文中一共展示了SqliteDatabase.close方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: wrapper
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import close [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
示例2: test_writes_db_to_archive
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import close [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")
示例3: DBProxy
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import close [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
示例4: TestManage
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import close [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)
示例5: bundle_language_pack
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import close [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
示例6: empty
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import close [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
)
)
示例7: bundle_language_pack
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import close [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
示例8: SqliteDatabase
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import close [as 别名]
app.config.from_object('settings')
database = SqliteDatabase(app.config['DATABASE'], threadlocals=True)
from mhvdb2.admin import admin # noqa
app.register_blueprint(admin, url_prefix='/admin')
@app.before_request
def before_request():
g.db = database
g.db.connect()
@app.after_request
def after_request(response):
g.db.close()
return response
import mhvdb2.routes # noqa
from mhvdb2.models import Entity, User # noqa
database.connect()
if not Entity.table_exists():
Entity.create_table()
if not User.table_exists():
User.create_table()
database.close()
示例9: get_user
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import close [as 别名]
database = db
def get_user(user_id):
try:
user = User.get(User.id == user_id)
except User.DoesNotExist:
user = User.get(User.id == 0)
return user
if __name__ == "__main__":
if User.table_exists():
print("Database Already Exists")
sys.exit()
db.connect()
db.create_tables([User])
User.insert_many([
{"id": 0, "name": "Invlid User", "langpair": "!!|!!"},
{"id": 120755813, "name": "Boris", "langpair": "ru|en"},
{"id": 93649293, "name": "Elizaveta", "langpair": "ru|en"},
{"id": 77815902, "name": "James", "langpair": "en|ru"},
{"id": 68382468, "name": "Jill", "langpair": "en|ru"},
{"id": 82080280, "name": "Kyle", "langpair": "en|ru", "admin": True},
{"id": 117778855, "name": "Mickey", "langpair": "en|ru"},
{"id": 97384423, "name": "Nataly", "langpair": "__|__"},
{"id": 96351689, "name": "Transbotor", "langpair": "!!|!!"},
]).execute()
db.close()
示例10: SqliteDatabase
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import close [as 别名]
import sqlite3
from peewee import Model, SqliteDatabase, DateTimeField, ForeignKeyField, FloatField, CharField
from datetime import datetime
DB = SqliteDatabase('finance-manager.db')
DB.connect()
class User(Model):
username = CharField(primary_key=True)
class Meta:
database = DB
class Amount(Model):
user = ForeignKeyField(User, backref='amount')
amount = FloatField()
date_time = DateTimeField()
class Meta:
database = DB
DB.create_tables([User, Amount])
DB.close()
示例11: Pomito
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import close [as 别名]
class Pomito(object):
"""Controls the application lifetime.
Responsibilities:
- Read and initialize the configuration
- Choose the run mode
- Handover execution to UI plugin
"""
def __init__(self, config=None, database=None, message_dispatcher=None):
"""Create a Pomito object.
Arguments:
config Configuration Path to the configuration file
database peewee.SqliteDatabase database to use for tasks etc.
message_dispatcher MessageDispatcher message dispatcher instance
"""
from pomito import pomodoro
self._config = config
self._database = database
self._message_dispatcher = message_dispatcher
self._threads = {}
self._hooks = []
if self._message_dispatcher is None:
self._message_dispatcher = MessageDispatcher()
if self._config is None:
self._config_file = os.path.join(CONFIG_DIR, "config.ini")
self._config = Configuration(self._config_file)
self._config.load()
# Pomodoro service instance. Order of initializations are important
self.pomodoro_service = pomodoro.Pomodoro(self)
# Default plugins
pomito.plugins.initialize(self.pomodoro_service)
self.ui_plugin = pomito.plugins.get_plugin(self._config.ui_plugin)
self.task_plugin = pomito.plugins.get_plugin(self._config.task_plugin)
# Add the plugins to threads list
self._threads['task_plugin'] = threading.Thread(target=self.task_plugin)
# Default hooks
from pomito.hooks import activity
self._hooks.append(activity.ActivityHook(self.pomodoro_service))
return
def initialize(self):
"""Initialize configuration, database and starts worker threads."""
os.makedirs(DATA_DIR, exist_ok=True)
database_path = os.path.join(DATA_DIR, "pomito.db")
if self._database is None:
self._database = SqliteDatabase(None)
self._database.init(database_path)
self._database.connect()
# Initialize the plugins
self.ui_plugin.initialize()
self.task_plugin.initialize()
# Initialize the hooks
for hook in self._hooks:
hook.initialize()
return
def run(self):
"""Start the application."""
if not self._validate_state():
logger.critical("Pomito.Run: Invalid state. Exiting.")
return
self.initialize()
self._message_dispatcher.start()
self.ui_plugin.run()
self.exit()
def exit(self):
"""Clean up and save any configuration data. Prepare for exiting the application."""
if self._message_dispatcher.is_alive():
self._message_dispatcher.stop()
self._message_dispatcher.join()
for hook in self._hooks:
hook.close()
if self._database is not None:
self._database.close()
def get_db(self):
"""Get the database object.
Returns:
database peewee.SqliteDatabase object
"""
return self._database
def get_configuration(self):
return self._config
def queue_signal(self, message):
#.........这里部分代码省略.........
示例12: TestBase
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import close [as 别名]
class TestBase(unittest.TestCase):
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)
def setUp(self):
self.app = app.test_client()
self.populate_database()
def request(self, method, url, auth=None, json_data=None, **kwargs):
headers = kwargs.get('headers', {})
if auth:
# Add the auth header if credentials are specified.
headers['Authorization'] = 'Basic %s' % b64encode(bytes(auth[0] + ':' + auth[1], 'utf-8')).decode('ascii')
if json:
headers['Content-Type'] = 'application/json'
kwargs['data'] = json.dumps(obj=json_data)
#print(kwargs['data'])
kwargs['headers'] = headers
#print(kwargs['headers'])
return self.app.open(url, method=method, **kwargs)
示例13: TestModel
# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import close [as 别名]
class TestModel(unittest.TestCase):
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)
def tearDown(self):
self.db.close()
self.db = None
def test_group_get(self):
os = Group.select()
self.assertEqual(len(os), 3)
o = Group.select().where(Group.name == 'group0name').get()
self.assertEqual(o, self.group0)
o = Group.select().where(Group.id == self.group0.id).get()
self.assertEqual(o, self.group0)
self.assertTrue(o.owner_id)
def test_group_memberships(self):
self.assertTrue(self.group0.is_member(self.user0))
self.assertTrue(self.group0.is_member(self.user1))
self.assertTrue(self.group1.is_member(self.user0))
self.assertFalse(self.group1.is_member(self.user1))
self.assertFalse(self.group2.is_member(self.user0))
self.assertTrue(self.group2.is_member(self.user1))
def test_get_reg_ids_by_user_id(self):
user_id = self.user0.id
devices = Device.select(Device, User).join(User).where(User.id == user_id)
self.assertEqual(len(devices), 1)
reg_ids = [d.reg_id for d in devices]
self.assertEqual(reg_ids, ['device0regid'])