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
Chris Freeman
Treehouse Moderator 58,993 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(
...     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])

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

thank you