7
votes

Basically, I am trying to share as much database layer code as possible between a Flask application (for a REST API) and a non-Flask API.

Is it a good idea to use the same Flask-SQLAlchemy layer in both the pure Python API (intended to be imported in non-web Python applications) and in the REST API Flask daemon?

I guess another way to phrase, though I am not sure on the terminology, "how do I best share database model between Flask app and a separate Python import library?"


Or from another angle, is there any point in using Flask-SQLAlchemy in a Flask REST API, if you also want to share the SQL abstraction with an import library. Is it better then to use plain SQLAlchemy?

Use case: we have a large database with many tables, and want to build both a REST API (for customer access) and a Python import library (for performant internal tools) for accessing the database, but of course share as much code between them as possible.

Related:

1
You have three choices: 1.) Set up your database layer using Flask-SQLAlchemy, and use the Flask app context as part of your library. 2.) Create two separate code bases (Flask and non-Flask). 3.) Build a common library, but make the use of the library depend on passing the SQLAlchemy session to it (using something like dependency injection). In your Flask process, initialize the library using the Flask app context. Otherwise, set up the SQLA session in your other program. Which of these three methods you choose is going to be very specific to your environment, so there's no "right" answer.Mark Hildreth
I am working on 3.) but could not find a nice solution so far ... stackoverflow.com/questions/64320876/…Joe
I found a nice solution: stackoverflow.com/a/64668814/7919597Joe

1 Answers

5
votes

Using Flask-SQLAlchemy models out of a web context is a matter of creating a Flask application and call

app.test_request_context().push()

The point here is what you will do with your "non web" library. If it's not a problem to have the whole Flask library installed when you need to use the library then there's no problem at all using it in that way.

If you plan to make performance improvements in the library data accessing code, like using different sessions, concurrency and such, then you're modifying your initial code so it's a totally different scenario. In this case a pure-SQLAlchemy approach might be better but it really depends on the differences between the two patterns.

Normally with models comes methods and using 2 different ORM patterns (Flask-SQLAlchemy wrapper models and pure SQLAlchemy) means duplicating code.