Preparing Your SQLite Database
The first argument is a database URL, which you receive from
db_url of the settings. You set
False because you’re working with a SQLite database. With this connection argument, SQLite allows more than one request at a time to communicate with the database.
declarative_base function returns a class that connects the database engine to the SQLAlchemy functionality of the models. You assign
Base will be the class that the database model inherits from your
models.py file. While
database.py contains information about the database connection, the
models.py file will describe the content of the database.
The code that you add to
models.py looks similar to the code that you wrote in
schemas.py, you define what data your API expected from the client and the server. In
models.py, you declare how your data should be stored in the database.
It’s common to give your model a singlular name and your database tables plural names. That’s why you name your model
URL and provide the special variable
__tablename__. Next you define
id as your database’s primary key. By setting the
primary_key argument to
True, you don’t need to provide a
unique argument, as it defaults to
True for primary keys.
secret_key columns will also contain unique entries. The
key field will contain the random string that will be part of the shortened URL. With
secret_key, you can provide a secret key to the user to manage their shortened URL and see statistics. Here, you define the column
target_url to store the URL strings for which your app provides shortened URLs.
03:36 Your app’s expected behavior is that any user can create a shortened URL for any target URL without knowing if such a forward already exists. So while you’ll provide a unique shortened URL, multiple shortened URLs may forward to the same address.
As you’ll see later, the
is_active Boolean column will come in handy when users want to delete a shortened URL. Instead of giving the user the power to delete a database entry directly, you’ll make the entry inactive instead. That way, you’ll have a safety net for critical actions, and you can undo the deletion if it was triggered accidentally. Finally, you define the
clicks column, which starts with zero. Later on in the course, you’ll increment this integer each time someone clicks the shortened link.
Become a Member to join the conversation.