web2py db is not defined

2019-07-14 04:53发布

I'm trying to run a script at command line that uses the models with the following command:

c:\web2py>python web2py.py -M -N -S automate -R applications/automate/modules/eventserver.py

but I keep getting the error:

web2py Web Framework
Created by Massimo Di Pierro, Copyright 2007-2011
Version 1.99.7 (2012-03-04 22:12:08) stable
Database drivers available: SQLite3, pymysql, pg8000, IMAP
Traceback (most recent call last):
  File "c:\web2py\gluon\shell.py", line 206, in run
    execfile(startfile, _env)
  File "applications/automate/modules/eventserver.py", line 6, in <module>
    deviceHandler = devicehandler.DeviceHandler()
  File "applications\automate\modules\devicehandler.py", line 10, in __init__
    self.devices = self.getActiveDevices()
 File "applications\automate\modules\devicehandler.py", line 18, in getActiveDe
vices
    print db
NameError: global name 'db' is not defined

What am I doing wrong?

edit: From my research I have only found the solution "add -M to your command" but I've already done that and it still doesnt work.

edit2: I have db = DAL('sqlite://storage.sqlite') in my db.py so it should get loaded

标签: python web2py
1条回答
Viruses.
2楼-- · 2019-07-14 05:40

edit2: I have db = DAL('sqlite://storage.sqlite') in my db.py so it should get loaded

Assuming db.py is in the /models folder, the db object created there will be available in later executed model files as well as in the controller and view, but it will not be available within modules that you import. Instead, you will have to pass the db object to a function or class in the module. Another option is to add the db object to the current thread local object, which can then be imported and accessed within the module:

In /models/db.py:

from gluon import current
db = DAL('sqlite://storage.sqlite')
current.db = db

In /modules/eventserver.py:

from gluon import current
def somefunction():
    db = current.db
    [do something with db]

Note, if you do define the db object in the module, don't define it at the top level -- define it in a function or class.

For more details, see the book section on modules and current.

查看更多
登录 后发表回答