When you ran your application in the previous exercises you might have realized that there is no database file created in the application folder. The reason is simple: we need to explicitly initialize the database according to the models declared.
We can initialize our database in two ways:
- Using the interactive Python shell.
- In the command-line terminal, navigate to the application folder and enter Python’s interactive mode:$ python3
- Import the database instance
db
from app.py:
(this assumes the application file is called app.py)>>> from app import db - Create all database tables according to the declared models:>>> db.create_all()
- From within the application file.
After all the models have been specified the database is initialized by adding
db.create_all()
to the main program. The command is written after all the defined models.
The result of db.create_all()
is that the database schema is created representing our declared models. After running the command, you should see your database file in the path and with the name you set in the SQLALCHEMY_DATABASE_URI
configuration field.
Instructions
In the Terminal window, enter Python’s interactive mode by typing python3
.
While in Python’s interactive mode, import the database instance db
from the app.py file.
After the database db
instance is imported, type and run db.create_all()
. Check the file system (a folder icon on the top left corner of the code editor) and verify that a new file called myDB.db is created.