read Colander Schema from a config file or database

425 views Asked by At

I googled for a while but I could not find reference on how to retrieve a Colander Schema from a config file or from a database. I think this is not difficult to implement but I might have overlooked something. Maybe somebody has done or seen something like that and might share some insights.

Here a sample for a Colander Schema:

class PageSchema(colander.MappingSchema):
    title = SchemaNode(String(),
                       title='Page title',
                       description='The title of the page',
                       )
    description  = SchemaNode(String(),
                              title='A short description', 
                              description='Keep it under 60 characters or so',
                              missing = u'',
                              validator=colander.Length(max=79)
                              )
    body = colander.SchemaNode(colander.String(),
                               description='Tell the world',
                               missing = u'')
3

There are 3 answers

0
Tim Tisdall On

ColanderAlchemy may do what you need. It takes SQLAlchemy objects and generates a Colander schema from them. However, generating from an SQLAlchemy object isn't exactly "from a database".

0
Michael Merickel On

This is not supported by colander. The one thing I know of in this area is the "limone" package which does the opposite. It is able to generate arbitrary python objects from a colander schema.

0
Loïc Faure-Lacroix On

As micheal said, it might not be supported. If you really need it. Here is some pointers.

Save your schema in a database by name for example: "PageSchema". Save all of its record in the database with all the needed parameters.

You'd have to do something like that:

for row in rows:
    attrinbutes[row['name']] = build_attribute(row)

schemas[schema_name] = type(schema_name, (colander.MappingSchema,), attributes)
exec('%s = schemas[schema_name]' % schema_name)

In other words, it loads all attributes and build a class using the type operator. That kind of task is pretty simple and should work as good as the habitual class syntax. The exec call is just to push the name in locals. You could probably use locals()[schema_name] = schmea or even other scopes.

That way you can load schemas from anywhere if needed. You could build yourself a factory like:

  • schemas.get('PageSchema') that would return a schema if possible or None if not present.

That's pretty much it!