Welcome to the Treehouse Community
Looking to learn something new?
Maxim Andreev24,529 Points
While using peewee, why do I not need to reconnect to the db when calling a CRUD method.
I have 2 files:
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
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?
Kenneth LoveTreehouse 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.