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?
Chris FreemanTreehouse 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
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.