Webpy sessions: AttributeError: 'ThreadedDict' object has no attribute 'username'

女生的网名这么多〃 提交于 2019-12-08 07:39:18

问题


I am making a webapp in python using web.py, I have set up the tables and can login the user and everything, but the initializer for sessions doesn't seem to work.

I have the following in my code:

store = web.session.DBStore(db, 'sessions')
session = web.session.Session(app, store, initializer={'logged_in': 0, 'username': ''})

render = web.template.render('templates/', base='base', globals={'session': session, 'username': session.username})

But this throws the error: AttributeError: 'ThreadedDict' object has no attribute 'username'

What can be done? I basically just followed the example here:
http://webpy.org/cookbook/sessions


回答1:


I had the same issue, so i used the _initializer property to get session data.

Here's an example:

store = web.session.DBStore(db, 'sessions')
session = web.session.Session(app, store, initializer={'logged_in': 0, 'username': ''})

session_data = session._initializer
render = web.template.render('templates/', base='base', globals={'session': session_data, 'username': session_data['username']})

You can then access all the data you declared in the initializer from session. If anyone has a better way, please let me know.

PS: I know its late, but better late then never...




回答2:


Session is only loaded when request is processed, you cannot get its attributes during setup.




回答3:


You are trying to get a session variable before it's set.

I've noticed that session.username works in some circumstances. But under WSGI it fails.

This works fine and is in the webpy docs :

session.get('username', False)

Not :

session.username

If you want to use the presets in the initializer, use the method in @Antonis-kalou 's answer.

session_data = session._initializer
session.get('username', session_data['username'])


来源:https://stackoverflow.com/questions/8025011/webpy-sessions-attributeerror-threadeddict-object-has-no-attribute-username

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!