0

我已阅读http://webpy.org/cookbook/sessions_with_subapp。当我只有一个应用程序时,会话工作正常,但是当我创建一个子应用程序时,我遇到了错误 ~ ,详细信息如下:

main.py:_

import web
from sub import subapp
web.config.debug = False

urls = ("/sub",subapp,"/", "count",)

app = web.application(urls, globals())

db = web.database(dbn='sqlite', db='./session.db')
store = web.session.DBStore(db, 'sessions')
session = web.session.Session(app, store, initializer={'count': 0})

def session_hook():
    web.ctx.session = session

app.add_processor(web.loadhook(session_hook))

class count:
    def GET(self):
        session.count += 1
        return str(session.count)

if __name__ == "__main__":
    app.run()

subapp.py:_

import web

urls = ("/", "count",)

subapp = web.application(urls, globals())

session = web.ctx.session

class count:
    def GET(self):
        session.count += 1
        return str(session.count)

尝试运行时出错:

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    from sub import subapp
  File "/tmp/session/sub.py", line 9, in <module>
    session = web.ctx.session
AttributeError: 'ThreadedDict' object has no attribute 'session'
4

1 回答 1

0

您不能简单地分配session = web.ctx.session,因为此行仅在应用程序初始化期间执行,但ctx属性只能在请求时访问。您可以from web import ctx然后在所有子应用程序中使用ctx.session而不是。session

subapp.py示例:

import web
from web import ctx

urls = (
    "/", "count",
)

subapp = web.application(urls, globals())

class count:
    def GET(self):
        ctx.session.count += 1
        return str(ctx.session.count)
于 2013-04-19T05:45:06.633 回答