我使用 db / core.py
中的以下功能创建与数据库的连接from contextlib import contextmanager
import peewee
proxy = peewee.proxy()
@contextmanager
def get_database(distribution_type):
if distribution_type == "local":
yield peewee.MySQLDatabase("db_local", user="root", host="test-db", port="3306")
else:
yield peewee.MySQLDatabase("db_prod", user="root", host="prod_db", port="3306")
class BaseModel(peewee.Model):
class Meta:
database = proxy
后来我将此模块导入到
db / manager.py
from core import get_database, proxy
class DistributionManager(object):
def __init__(self, distribution_type="local"):
super(DistributionManager, self).__init__()
self._distribution_type = distribution_type
self._initialize_database()
def _initialize_database(self):
with get_database(self._distribuition_type) as db:
proxy.initialize(db)
def create(self, source, dest):
self._pw_model = DistributionModel.create(source=source, dest=dest)
所以我的问题是,当db不公开时如何显式调用db.close()
?
答案 0 :(得分:0)
您应该能够调用proxy.close()
,它将把close()调用分派给数据库对象。