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?"
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With