3

I'm pretty new to Pyramid, and I can't figure out how to use the autoload=true option in Pyramid. I used the pyramid_routesalchemy to create my project using paster.

The problem is that there is an init.py file which uses the initialize_sql (and this function defines Base.metadata.bind = engine). In one of my model classes I would like to use the autoload=true option (using the declarative base), but I always get the following error:

sqlalchemy.exc.UnboundExecutionError: No engine is bound to this Table's MetaData. Pass an engine to the Table via autoload_with=<someengine>, or associate the MetaData with an engine via metadata.bind=<someengine>

Actually Base.metadata.bind = engine is defined inside the initialize_sql function and I do not realy know in which order the file are loaded, but I'm almost sure that that init.py is loaded before the model, and thus metadata was already binded to the engine...

Thus, my question: how can use autoload within my classes without changing the whole init and model structure ?

If anyone has a hint... Thanks in advance

tshepang
  • 12,111
  • 21
  • 91
  • 136
kalbermattenm
  • 53
  • 1
  • 6
  • Okay... I found a way to avoid having an error (but I don't really know if I just do it like that...). I just separated the model classes (in a new .py file) from the DB init stuff. And I just call this new file from my view. It works, but I'm not sure that this is the best way to do it... – kalbermattenm Oct 18 '11 at 06:32
  • Possible duplicate of [SQLAlchemy declarative syntax with autoload (reflection) in Pylons](http://stackoverflow.com/questions/4526498/sqlalchemy-declarative-syntax-with-autoload-reflection-in-pylons) – Piotr Dobrogost Aug 23 '16 at 09:26

2 Answers2

1

From SQLAlchemy 0.8 you can use the DeferredReflection class when creating your declarative base to delay the autoload until an engine is attached to your metadata:

from sqlalchemy.ext.declarative import declarative_base, DeferredReflection

Base = declarative_base(cls=DeferredReflection)

See here: http://docs.sqlalchemy.org/en/rel_0_8/orm/extensions/declarative.html#using-reflection-with-declarative

rachekalmir
  • 614
  • 1
  • 8
  • 17
1

Yeah, the basic idea here is that the autoloaded tables cannot be declared without a valid engine, so you need to separate your initialization code from your model code and ensure that the models aren't imported until you have setup the engine and connected it to the metadata.

The link below describes it better, but it looks like you've already taken the correct approach.

SQLAlchemy declarative syntax with autoload (reflection) in Pylons

Community
  • 1
  • 1
Michael Merickel
  • 23,153
  • 3
  • 54
  • 70