On Sunday, December 18, 2011 2:07:40 PM UTC-8, Jonathan Vanasco wrote:
>
> ...
>
> 2. Have my models reflect the database.  With some custom routines, I
> largely just had to pass in a string for the tablename and a sometimes
> primary key .
>
> I'm not sure how to do that under Pyramid ( I am using the Akhet
> scaffold ).
>

I'm using database reflection quite happily in a project. I started from a 
pyramid_routesalchemy scaffold, so I'm not sure how applicable the 
following is to an Akhet project, but I suspect there is some common ground.

In my models.py module I created a ReflectedTable class to handle the 
reflection and mapper setup, a bunch of class stubs that inherit from it, 
and a map_tables function that gets called in initialize_sql() to make 
everything happen:

from sqlalchemy import Table
from sqlalchemy import MetaData
from sqlalchemy.orm import mapper
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import sessionmaker
from zope.sqlalchemy import ZopeTransactionExtension

DBSession = 
scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
metadata = MetaData()

class ReflectedTable(object):
    """Base class for database objects that are mapped to tables by
    reflection.
    """
    @classmethod
    def map_by_reflection(cls, table_name):
        """Map the specified database table to the object by
        reflection.
        """
        table = Table(table_name, metadata, autoload=True)
        mapper(cls, table)

class SomeTable(ReflectedTable): pass

class SomeOtherTable(ReflectedTable): pass

def map_tables():
    objs_and_tables = [
        (SomeTable, 'some_table_name'),
        (SomeOtherTable, 'some_other_table_name'),
    ]
    for obj, table_name in objs_and_tables:
        obj.map_by_reflection(table_name)

def initialize_sql(engine):
    DBSession.configure(bind=engine)
    metadata.bind = engine
    map_tables()

initialize_sql gets called in __init__.main() so the reflection is all done 
during app startup. I suspect that's where you would want to do your 
multiple engine setup too, but I've never tried that.

Hope that helps...

-- 
You received this message because you are subscribed to the Google Groups 
"pylons-discuss" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/pylons-discuss/-/ky927sRGu4wJ.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en.

Reply via email to