我看过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'
答案 0 :(得分: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)