Search code examples
pythonpeewee

How to close the database connection in peewee from mysql explicitly


I create connect to db using the below function in 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

later I import this module to

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)

so my question is how do I call db.close() explicitly when db is not public ?


Solution

  • You should be able to call proxy.close(), which will dispatch the close() call to the database object.