Setting up SQLAlchemy
Before we dive into how to create optimal database models for your application to promote efficient large-scale database operations, we will first need to set up our ORM solution. Since we are going to use SQLAlchemy here, let's see how we can set it up in our development environment.
For SQLAlchemy to work, you should have a database management system setup, either on your system or a remote machine, that you can connect to. A container with an exposed port will also get the work done for us. To keep the examples simple, we assume the reader is using PostgreSQL as their database solution here, and is knowledgeable about how the PostgreSQL setup works. Now, let's see how we can set up SQLAlchemy:
mkdir ch3 && cd ch3
virtualenv --python=python3 .
source bin/activate
pip install sqlalchemy psycopg2
Let me explain what we did here. We first created a directory for this chapter and then initialized a Python 3-based virtual environment inside the directory. The next thing we did was to activate that virtual environment. This allows us to keep the changes the Python packages make segregated into one place so that they don't affect the whole system (which is the preferred way and prevents you from getting any surprises due to broken dependencies for other Python projects that may be living on your system).
Once our virtual environment is activated, we move on and install the Python SQLAlchemy library and the pyscopg2 Python package, which provides Python bindings for PostgreSQL in Python, and which is also a requirement for connecting to a PostgreSQL database using SQLAlchemy.
Now, with the SQLAlchemy setup complete, we are ready to dive into the world of database modeling with ORM solutions.