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 Using Databases in Python Our Diary App Doing Data Entry

Would there ever be a case not to use Safe=True?

Safe=True is a pretty nifty parameter. Is it okay to just always use it, or would there be instances when it should not be used?

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

When using the safe parameter, you get no feedback whether the table was actually created or the command "safely" silently did nothing. Without using safe, an OperationalError could be raised if the table already existed. Sometimes you might want the error to be raised so you can handle it in your own manner.

>>> from peewee import *
>>> db = SqliteDatabase('foo.db')
>>> db.connect()
>>> class Post(Model):
...     timestamp = DateTimeField(default=datetime.datetime.now)
...     content = TextField()
...     class Meta:
...         database = db
...         order_by = ('-timestamp',)
... 
>>> db.create_tables([Post,])
>>> Post.create(content="some data")

# Try creating the table again with 'safe'
>>> db.create_tables([Post,], safe=True)
>>>  # no output

# by not using 'safe' other actions can be done
>>> try:
...     db.create_tables([Post,])
... except OperationalError:
...     print("Sorry Table already exists!")
... 
Sorry Table already exists!

From the docs

  create_tables(models[, safe=False])
    Parameters: 

        models (list)  A list of models.
        safe (bool)  Check first whether the table exists before attempting to create it.

thank you