Do peewee models automatically close the connection?
Asked Answered
Y

3

11

I am using peewee to access a SQLite DB.

I have made a model.py like:

from peewee import *

db = SqliteDatabase('people.db')

class Person(Model):
    name = CharField()
    birthday = DateField()
    is_relative = BooleanField()

    class Meta:
        database = db

In another Python file (with import model) I then manipulate the DB with calls like Person.create() or Person.select(name=='Joe').delete_instance().

The Quickstart says at the end to call db.close() to close the connection. Does this apply to my case as well? Am I supposed to call something like model.db.close()?

Yolandayolande answered 19/1, 2017 at 8:7 Comment(1)
may i know what is_relative attribute will do(what's the use of it)...??Disburse
T
10

According to Charles Leifer, the maker of peewee, it is the programmer's job to terminate connections. The documentation about Connection Pools tells that all connections are thread-local, so as long as the Model is in use, the connection stays open, and dies when the thread containing the Transaction joins the Main-Thread.

Charles explicitly answers a question about the Connection Pool. The answer is a bit generalized, but I suppose this applies to all connections equally: About connection pool

Implicit answers on the topic:

Error 2006: MySQL server has gone away

Excerpt from the docs Quickstart Page:

Although it’s not necessary to open the connection explicitly, it is good practice since it will reveal any errors with your database connection immediately, as opposed to some arbitrary time later when the first query is executed. It is also good to close the connection when you are done – for instance, a web app might open a connection when it receives a request, and close the connection when it sends the response.

The final answer to your question is, based on these information: No.

Term answered 11/10, 2017 at 6:49 Comment(0)
S
3

You open and close the connection manually:

In your case (with db = SqliteDatabase('people.db'))

you established connection with the database by:

db.connect()

next you do whatever you want with the database and finally you close the connection with:

db.close()
Stannic answered 20/1, 2017 at 13:46 Comment(0)
C
0

Tracking down improperly closed database connections in an existing project can be quite challenging. Here is my approach, which I offer as a reference for those encountering the same issue:

Implementing with Python 2.7, I inspect the database connection during the destruction of a Peewee Model. If the connection remains open, a warning is issued along with the traceback; however, scenarios within the with database: context are bypassed.

from playhouse.pool import PooledMySQLDatabase
from peewee import Model
import logging
import traceback

logger = logging.getLogger(__name__)

class TrackingDatabase(PooledMySQLDatabase):
    def __init__(self, *args, **kwargs):
        super(TrackingDatabase, self).__init__(*args, **kwargs)
        self._in_context = False

    def __enter__(self):
        self._in_context = True
        return super(TrackingDatabase, self).__enter__()

    def __exit__(self, exc_type, exc_val, exc_tb):
        self._in_context = False
        return super(TrackingDatabase, self).__exit__(exc_type, exc_val, exc_tb)

    @property
    def in_context(self):
        return self._in_context

database = TrackingDatabase(....)

class BaseModel(Model):

    class Meta:
        database = database

    def __del__(self):
        if not database.is_closed() and not database.in_context:
            stack = "".join(traceback.format_stack())
            logger.warning("Database connection remains open.\n%s", stack)

Then wrap the warning part in a with database: context to ensure the connection is closed properly.

Coombs answered 5/6 at 4:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.