سؤال

I have read http://webpy.org/cookbook/sessions_with_subapp. The session works fine while I have only one app, but when I create a sub app, I am encountering error ~ ,details below:

The 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()

The 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)

Errors while try to run:

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'
هل كانت مفيدة؟

المحلول

You can't simply assign session = web.ctx.session because this line is executed only during app initialization but ctx attributes are only accessible at request time. You may from web import ctx and then use ctx.session instead of session in all subapps.

subapp.py example:

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)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top