Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving SQLAlchemy models to file

I'm coming from EntityFramework. I'm used to creating my db, running EF, and having a bunch of class files generated for each of my db objects (usually tables) filled with properties (usually columns).

Following this basic use example, I've figured out how to use reflection to generate models in memory. But how does one save the models to disk as classes? Since python code isn't compiled I guess the entire ORM could just be generated every time I run my application, but this feels very strange coming from my EF background. What's the best practice here? (BTW I'm using this in the context of Flask).

like image 716
xavier Avatar asked Oct 20 '22 07:10

xavier


1 Answers

Generally you reflect them every time you run your app, yes. Otherwise they'd break when you update your schema, which would sort of defeat the point of using reflection.

It is possible to generate declarative classes based on the current state of your schema; there's a sqlacodegen module on PyPI that does this, and the author of SQLA has a database migration project called Alembic that tackles the similar problem of comparing two schemata.

like image 173
Eevee Avatar answered Oct 23 '22 04:10

Eevee