Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


Maxim Andreev
Maxim Andreev
24,529 Points

While using peewee, why do I not need to reconnect to the db when calling a CRUD method.

I have 2 files:

main_prog.py support_func.py

In support_func I declare all the classes for my db, as well as setup the db itself. I also have a ton of functions that I use in other modules.

#  support_func
db = SqliteDatabase('~/somefile.db')

class Example(Model):
    var1 = PrimaryKeyField()
    var2 = BooleanField()
    # etc, there are of course many more tables

def myFunc(arg1):
    return_var = Example.select().where(
        Image.var == arg1).first().var2
    return return_var

def create_db():
    db.create_tables([Example], safe=True)

def main():

if __name__ == '__main__':

Then in main_prog I simply

#  main_prog
from support_func import myFunc

def main():

if __name__ == '__main__':

Now my question is, to setup the db initially I need to use


How come I do not need to use that when calling myFunc() ?

Also, I imagine the db disconnects automatically and I do not need to worry about closing the connection?

Thank you

1 Answer

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Peewee is actually smart enough to connect on its own, IIRC. That said, it's usually better to be explicit so it's a good idea to do a db.connect() before you run a CRUD command anyway.