Код: Выделить всё
# Checking if the database has tables
inspector = inspect(engine)
tables = inspector.get_table_names()
print(tables) # Should be "[]"
if not (tables):
# There are no tables in the database.
db.create_all()
db.session.commit()
print("Created database tables.")
del inspector
Код: Выделить всё
with engine.connect() as connection:
# Iterating through all the tables in the database...
inspector = inspect(engine)
tables = inspector.get_table_names()
print(tables) # Should return something like ['users', 'posts']
for table_name in tables:
# Does this table have any rows?
result = connection.execute(
"SELECT COUNT(*) FROM {}".format(table_name))
for row in result:
if row[0] == 0:
# This table doesn't have any rows.
# So we fill it...
del inspector
Есть ли лучший способ выполнения этой процедуры, который не требует мне удалить объект инспектора и воссоздать его? У меня такое ощущение, что это не лучшая практика.
Подробнее здесь: https://stackoverflow.com/questions/701 ... sqlalchemy
Мобильная версия