Setting Up SqlAlchemy To Use Multiple Databases

In my latest project, PriceMind I wanted to make the database more scalable. I had one database used by Flask. Inside that one db I had the tables a user needs to reach. Also, I had the users table inside this db. But it was dumb because each user has to have its own database with its own tables in order to scale properly. But then how do I access the users table? Should I create a new database for user table?

sqlalchemy multiple db

Setting Up SqlAlchemy To Use Multiple Databases

So I realized that in order to have a scalable system I need to have a separate database only to store user information like email, name etc. Considering my stack, I had to research how to setup SqlAlchemy and Flask to use multiple databases. One for user management. One for querying user-specific data.

 

SQLAlchemy Binding

You can setup an arbitrary number of separate databases with SQLAlchemy. You just have to “bind” each database URI to a unique name. So when you create a db model in your application you need to bind which database to use. Otherwise the one will be used which is defined by SQLALCHEMY_DATABASE_URI.

 

SQLAlchemy Config

In my application I have a file which contains the configuration settings for SQLAlchemy.

As you can see, I defined SQLALCHEMY_DATABASE_URI which is dynamically created so it always uses the db which belongs to the current user.

Also, I defined two binds in SQLALCHEMY_BINDS. One for users table and another one for heavy data tables. But I only need to explicitly bind the users db because the other one is used by default.

User Model Binding

So we’ve created the binds, now invoke it in the db model.

This is a pretty basic user model in my app.

Simply, using __bind_key__ we’ve told SQLAlchemy to use the users database to manage users. If we don’t define a bind SQLALCHEMY_DATABASE_URI will be used.

 

Download FREE ebook!