Search code examples
postgresqlsqlalchemyspyne

Spyne model for existing Database structure


I have an issue with defining model in spyne to generate several levels "in" SOAP11. I used example at first, but my task is to generate service for tables already existing, so I got stuck and try to understand wheter to seek in Spyne properties or Sqlalchemy.

To be precise, i'll take example from site and show what i'm trying to reach:

class Permission(TableModel):
__tablename__ = 'permission'

id = UnsignedInteger32(pk=True)
application = Unicode(values=('usermgr', 'accountmgr'))
operation = Unicode(values=('read', 'modify', 'delete'))
perm_user_id = integer

last field is the FK for user table, but its name is different from user_id

class User(TableModel):
__tablename__ = 'user'

id = UnsignedInteger32(pk=True)
user_name = Unicode(32, min_len=4, pattern='[a-z0-9.]+', unique=True)
full_name = Unicode(64, pattern='\w+( \w+)+')
email = Unicode(64, pattern=r'[a-z0-9._%+-]+@[a-z0-9.-]+\.[A-Z]{2,4}')
last_pos = Point(2, index='gist')
permissions = Array(Permission).store_as('table')

--- SQL generated tries to add "WHEN user.id = permission.user_id" but I need another field (perm_user_id) to be filtered

Help me to define class to get correct inner tags.. actually it'll be about 3 more classes deep.

Thanx in Advance, Yury


Solution

  • Your answer is correct. Just as an alternative for simple tables, you can omit column definitions and let sqlalchemy's reflection engine figure it out.

    meta = TableModel.Attributes.sqla_metadata
    meta.reflect()
    class User(TableModel):
        __table__ = meta.tables['user']
    

    The User class will be reconstructed using as much information as possible from the table columns and their types.