【发布时间】:2014-09-16 06:03:44
【问题描述】:
使用 Cherrypy/MySQL 设置 MVC 设计时出现问题。这是设置:(假设所有导入都是正确的)
##controller.py
class User(object):
def __init__(self):
self.model = model.User()
@cherrypy.expose
def index(self):
return 'some HTML to display user home'
## model.py
class Model(object):
_db = None
def __init__(self):
self._db = cherrypy.thread_data.db
class User(Model):
def getuser(self, email):
#get the user with _db and return result
##service.py
class UserService(object):
def __init__(self):
self._model = model.User()
def GET(self, email):
return self._model.getuser(email)
##starting the server
user = controller.User()
user.service = service.UserService()
cherrypy.tree.mount(user, '/user', self.config)
#app.merge(self.config)
cherrypy.engine.subscribe("start_thread", self._onThreadStart)
self._onThreadStart(-1)
def _onThreadStart(self, threadIndex):
cherrypy.thread_data.db = mysql.connect(**self.config["database"])
if __name__ == '__main__':
cherrypy.engine.start()
cherrypy.engine.block()
上面的代码在model.py中的行有错误:cherrypy.thread_data.db。 我得到了:
AttributeError: '_ThreadData' object has no attribute 'db'
不知道为什么,请您指出正确的方向吗?我可以获取连接,并从用户索引处的 controller.py 中提取信息,但不能在 model.py 中? 请帮忙..谢谢。
【问题讨论】: