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

Build A Social Network with FLASK ---> Purpose of constantly calling models.initialize()

Why did we put models.initialize() in to run every time app.py is run? Aren't the models(tables) already in the database?

1 Answer

Ryan S
Ryan S
27,276 Points

Hi Rastko,

def initialize():
    DATABASE.connect()
    DATABASE.create_tables([User, Post, Relationship], safe=True)
    DATABASE.close()

If you look at the .create_tables() line, you'll see the "safe=True" parameter. This is basically the Peewee version of SQL's "IF NOT EXISTS" command when creating a table. So in this case, models.intialize() serves 2 purposes: the first is to check if the tables already exist, and the second is to create them if they don't. If they do exist then everything's ok, it'll just move on. This is like a safety measure in case something happened to your existing database. Maybe it got deleted or changed in some undesirable way.

I hope this answers your question.