Published in 14:27 of 08/15/2012 by

Published in 14:27 of 08/15/2012

←Home

Lazy DAL - Attempt 3 - Pbreit

based on Pbreit request

On Wed, Aug 15, 2012 at 2:32 PM, pbreit wrote:
What would it take to set it up such that models are defined in mostly the same way as now but in "module" files and then imports are done in controllers/functions that need access to the table.

This file goes on modules/mymodels.py

# -*- coding: utf-8 -*-

from gluon.dal import DAL, Field
from gluon import current

DBURI = "sqlite://....."

TABLE_DEFINITIONS = {
    "owners": {
        "fields": [Field("name")],
        "kwargs": dict(format="%(name)s")       
    },
    "cars": {
        "fields": [Field("name"),
                   Field("owner", "reference owner")],
        "kwargs": dict(format="%(name)s")       
    }
}

class Models(object):
    def __init__(self):
        self.db = DAL(DBURI)

    @property 
    def tables(self):
        return self.db.tables

    def __call__(self, *args, **kwargs):
        return self.db(*args, **kwargs)

    def table_definer(self, tablename):   
      if not tablename in self.db.tables:
          fields = TABLE_DEFINITIONS.get(tablename, {}).get('fields', [])
          kwargs = TABLE_DEFINITIONS.get(tablename, {}).get("kwargs", {})
          return self.db.define_table(tablename, *fields, **kwargs)
      return self.db[tablename]

    def __getattr__(self, key):
      if hasattr(self.db, key):
          return getattr(self.db, key)
      elif key not in TABLE_DEFINITIONS.keys():
          raise AttributeError("attr not found")
      else:
          return self.table_definer(key)

Now in any controller controllers/default.py

from mymodels import Models()
db = Models()

def list_owners():
    rows = db(db.owners).select()
    return dict(rows=rows)

I tested and works, the only caveat is that you are not going to use db.define_table but you will put your model definitions on TABLE_DEFINITIONS dict

  • Programmatically check if Django South has migrations to run in django · 23:48 of 01/03/2013
  • App news reading (portuguese) in web2py · 20:08 of 09/11/2012
  • Open links which points outside your own site in a new window in python · 00:43 of 08/14/2012

  • comments powered by Disqus Go Top