Как закрыть соединение с базой данных в peewee из mysql явно - PullRequest
0 голосов
/ 27 сентября 2018

Я создаю соединение с БД, используя следующую функцию в 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

, позже я импортирую этот модуль в

дБ /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.close(), когда db не публичен?

1 Ответ

0 голосов
/ 28 сентября 2018

Вы должны быть в состоянии вызвать proxy.close(), который отправит вызов close () объекту базы данных.

...