How to create a python rest API that supports multiple databases

Question:

Here’s my set up:

I have a django application that has 2 users: Bob and Jake

Both Bob and Jake have a specific database associated with them for security purposes. In other words, if Bob is logged in, then all rest API calls made by Bob should be directed at his own database (he should not be able to access Jake’s) and vise-versa.

I’m wondering how to set this type of API up, where depending on the person logged in, the request is routed to the correct database.

Furthermore, I ideally would like this API completely decoupled from my django application (it should live as an entirely separate application).

I’m wondering if anyone has any suggestions on how to set this type of API up? I’m open to using flask, django, etc…

Thanks for your help!!

Asked By: diego_c

||

Answers:

You can handle this pretty easily with Flask and SQLAlchemy. Create different SQLAlchemy engines pointing to different databases, create sessions off those engines, and use them accordingly.

SQLAlchemy setup code:

bob_engine = create_engine('sqlite:////bob.db')
BobSession = scoped_session(sessionmaker(autocommit=False,
                                     autoflush=False,
                                     bind=bob_engine))
jake_engine = create_engine('sqlite:////jake.db')
JakeSession = scoped_session(sessionmaker(autocommit=False,
                                     autoflush=False,
                                     bind=jake_engine))

Flask endpoint, using Flask-Login’s current_user object:

@app.route('/foo')
def foo():
   if current_user.name == 'Jake':
        session = BobSession()
   else:
        session = JakeSession()
   # run some query with the session...
   session.close()
Answered By: jumbopap
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.