Interesting.  I wonder why my modules are working when I just pass the
db to the functions within them?

On 1.99.2 I have something like this working.

mymodule.py contains no classes, just some functions.  One looks like
this:

def myfunction(db, request, session, some_value):
  query = db[request.controller].somefield==somevalue
  rows = db(query).select(
   db[request.controller].field_1,
   db[request.controller].field_2,
  )
  tbl = TABLE()
  for row in rows:
    tbl.append(row.field_1....
  return tbl

Then in the controller I do this:

def index:
  import mymodule
  somevalue = 'foo'
  return dict(form=mymodule.myfunction(db,request,session,somevalue))




On Feb 24, 10:40 am, Johann Spies <johann.sp...@gmail.com> wrote:
> On 24 February 2012 16:58, JaapP <j...@tetra.nl> wrote:
>
>
>
>
>
>
>
>
>
> > Hi All,
>
> > i've been struggling with the following problem for some time and hope
> > anyone can help.
>
> > When i instantiate a class in a controller (class is in separate file in
> > Modules folder) and i want to use the database from within this instance, i
> > have to pass the DB to the class.
>
> > Inside this instance, querying the db works normal.
> > But, when i try to insert a new record into the database the database
> > (sqlite) is not updated.
>
> > Debugging shows me that the db object inside the instance is actually
> > updated.
>
> > So my question: how should i use the web2py database connection inside a
> > class? As far as i can understand when passing the DB to a class this
> > creates a new DB object that is not connected to the file store..
>
> > Any help greatly appreciated!
>
> I have asked a similar question a week or two ago on this list.  If you
> search the list, you will find the thread.
>
> In my module I have
>
> from gluon import *
>
> class Univ(object):
>
>     def __init__(self, db,):
>         self.db = db
>
> and I create an instance of this class in the controller using
>
> t = Univ(db)
>
> also in other modules I use the following inside functions (read the book
> about this: you should not use this as a global variable in a module:
>
> def somefunction():
>
>    db = current.db
>
> while I have in models/db.py (after the connection to the database was
> defined):
>
> from gluon import current
> current.db = db
>
> Regards
> Johann
>
> --
> Because experiencing your loyal love is better than life itself,
> my lips will praise you.  (Psalm 63:3)

Reply via email to