[Zope3-Users] Draft how-to: generation of interface schemas from a YAML file

Petri Savolainen petri.savolainen at iki.fi
Fri Jan 14 07:14:56 EST 2005


Here's a simple how-to on how to generate interface schemas from data in
a YAML file. Thanks to Marius Gedminas for a bit of python magic.

Here's an example YAML definition for IPerson:

--------- 8-< ----- file:schemata.yml ---------------
---
IPerson:
    -first:
       type: TextLine
       title: First name
       description: The first name of the person
    -last:
       type: TextLine
       title: Last name
       description: The last name of the person

--------- 8-< ---------------------------------------


Here's an example interface definition:

from util import setSchema
class IPerson(interface):
    setSchema("schemata.yml")

And here's the code. You also need the PyYaml package installed, from
http://www.pyyaml.org.

--------- 8-< ----- file:util.py --------------------

def getSchemaFields(filename,schemaname):

    source = yaml.loadFile(filename)

    for s in source:
       try:
          fields = s[schemaname]
          for f in fields:
             fname = f.keys()[0] # f is a dict with one key
             field = f.values()[0]

             fieldtype = field["type"]
             del field["type"]

             # Type casting...
             for attn in field:

                # cast 'default' values of Int fields to int
                if fieldtype=="Int" and attn == "default":
                   field[attn] = int(field[attn])

                # cast True/False in 'required' to bool
                elif attn == "required":
                   field["required"] = bool(eval(field["required"]))

                # cast other data to unicode
                else:
                   field[attn] = unicode(field[attn])

             yield fname, eval(fieldtype)(**field)

       except KeyError:
          pass


def setSchema(filename):
    caller = sys._getframe(1)
    schemaname = caller.f_code.co_name

    for name,field in getSchemaFields(filename, schemaname):
       caller.f_locals.update({name: field})

--------- 8-< ---------------------------------------



More information about the Zope3-users mailing list