pythonpeeweeflask-peewee

How to disable peewee's automatic connections?


Consider the following piece of code

import peewee

SQL_CONN = peewee.MySQLDatabase(database=SQL_DATA,
                                host=SQL_HOST,
                                port=SQL_PORT,
                                user=SQL_USER,
                                passwd=SQL_PASS)

class User(peewee.Model):
    name = peewee.CharField(max_length=100, primary_key=True)

    born = peewee.DateTimeField()

print(SQL_CONN.is_closed()) # True

print(User.select().where(User.name == "Jack").execute()) # Silently opens a connection w/o letting me know

print(SQL_CONN.is_closed()) # False

This will automatically perform SQL_CONN.connect() under the hood.

How do I disable this functionality - force peewee to just throw exceptions if the database is not connected - as opposed to automatically connecting to it without letting me know.


Solution

  • First off, your example is fake and wrong. Peewee does not open a connection when you merely create a query object. Check it out:

    In [1]: from peewee import *                                                                    
    
    In [2]: db = SqliteDatabase(':memory:')                                                         
    
    In [3]: class User(Model): 
       ...:     username = TextField() 
       ...:     class Meta: 
       ...:         database = db 
       ...:                                                                                         
    
    In [4]: db.is_closed()  # Should be True.                                                       
    Out[4]: True
    
    In [5]: query = User.select().where(User.username == 'charlie')                                 
    
    In [6]: db.is_closed()  # Still TRUE, we haven't evaluated anything yet!
    Out[6]: True
    

    So, first off, your example is not even correct. You would have to evaluate the query for it to execute.

    To answer the rest of this question:

    Peewee doesn't provide a mechanism to disallow implicit connections. If you attempt to execute a query, Peewee will open the connection if it does not exist.

    I'd suggest that it should be very clear when you execute a query, and hence - when you need to open a connection. If that's not enough, then subclass and override the Database.cursor() method.


    EDIT:

    Even though nobody has asked for this before, it's such a simple thing to implement that I've added this functionality to Peewee. Will be contained in the next release.