Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the same database abstraction in Flask and non-Flask program

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:

  • Using Flask-SQLAlchemy in Blueprint models without reference to the app
  • What's your folder layout for a Flask app divided in modules?
  • SQLAlchemy with Flask -- hybrid models?
like image 649
Prof. Falken Avatar asked Sep 03 '13 12:09

Prof. Falken


1 Answers

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.

like image 50
Paolo Casciello Avatar answered Sep 21 '22 19:09

Paolo Casciello