Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

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.connect()
    db.create_tables([Example], safe=True)

def main():
    create_db()


if __name__ == '__main__':
    main()

Then in main_prog I simply

#  main_prog
from support_func import myFunc


def main():
    myFunc(3)


if __name__ == '__main__':
    main()

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

db.connect()

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
STAFF
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.