Setting Up Database

The first thing we are going to do is to update our Config class in config.py with the following code :

Now we can add SQLAlchemy and Flask-Migrate in our project as :

Now, to define our database tables, we’ll create a models.py within the app package. Inside that, we can write the following code :

We first imported the db that we had initialized in the __init__.py. Then we created a ShortUrls class with few fields such as id(primary key), original_url(provided by the user), short_id(generated by us or provided by user), and created_at(timestamp).

We can then make use of Flask-Migrate commands to migrate the database with the new tables. The commands to be used are : 

flask db init — to initialize the database at the beginning(to be used only once)

flask db migrate — to migrate the new changes to the database(to be used every time we make changes in the database tables)

flask db upgrade — to upgrade our database with the new changes(to be used with migrate command)

After we run the database initialization we will see a new folder called “migrations” in the project. This holds the setup necessary for Alembic to run migrations against the project. Inside of “migrations”, we will see that it has a folder called “versions”, which will contain the migration scripts as they are created.

Discussion

1

0