set variable on models or modules

46 views
Skip to first unread message

黄祥

unread,
Jul 4, 2019, 3:23:43 PM7/4/19
to web2py-users
is there any difference to set variable on models or modules ?
e.g.
models/db_connect.py
db = DAL('sqlite://test.sqlite', pool_size = 1)

modules/db_connect.py
from gluon.dal import DAL
from gluon import current
db
= DAL('sqlite://test.sqlite', pool_size = 1)
cache
= current.cache
cache_time_expire
= 10
cache_model
= cache.ram # cache.ram, cache.disk, cache.memcache, cache.redis
cache_db
= (cache_model, cache_time_expire)

controllers/install.py
import db_connect
def index():
    db
= db_connect.db
    db_schema_1_address
.define(db = db)
    address_id_1
= db.address.insert(street = 'a', zip_code = '1', city = 'a', country = 'a')

controllers/api.py
import db_connect
#db = db_connect.db # not worked, must use from models/db.py
cache_db
= db_connect.cache_db # this variable can be used from modules, no error occured
db_schema_1_address
.define(db = db)

def response_json_rows():
   
if not request.env.request_method == 'GET': raise HTTP(403)
    table_name
= request.args(0)
    id
= request.args(1)
   
if id.isdigit() and int(id) > 0:
        query
= (db[table_name]['id'] == id)
   
else:
        query
= (db[table_name]['id'] > 0)
    rows
= db(query).select(orderby = ~db[table_name]['id'],
                            cache
= cache_db,
                            cacheable
= True)
   
return response.json(rows)

Traceback (most recent call last):
 
File "/Users/sugizo/learn/python/web2py/gluon/restricted.py", line 219, in restricted
   
exec(ccode, environment)
 
File "/Users/sugizo/learn/python/web2py/applications/test/controllers/api.py", line 24, in <module>
    db_schema_1_address
.define(db = db)
 
File "applications/test/modules/db_schema_1_address.py", line 64, in define
    format
= lambda r: \
 
File "/Users/sugizo/learn/python/web2py/gluon/packages/dal/pydal/base.py", line 581, in define_table
   
raise SyntaxError('table already defined: %s' % tablename)
SyntaxError: table already defined: address

any ideas ?
intention is to move define tables from models into modules and load it on controller when it's required, with minimal effort

thx n best regards,
stifan

Val K

unread,
Jul 4, 2019, 6:11:46 PM7/4/19
to web2py-users
It seems  that defining db=DAL(...) at module level is not  a good idea  
Reply all
Reply to author
Forward
0 new messages