session in webpy - getting username in all classes

2019-04-02 01:18发布

问题:

I am using webpy framework for my project. I am logging in from my 'login' class of main.py program. I want to get the username in some other class. I tried with session and experimented with it for a long time. I have implemented session like below.

store = web.session.DiskStore('sessions')
session = web.session.Session(app,store,initializer={'login': 0,'privilege': 0})

in my login class of main.py the following code will work when user submit username and password.(This is the post method 0f my login class).

class login:
    def POST(self):
            i = web.input(form_submit="Login")
            authdb = sqlite3.connect('database/users.db')
            conn = authdb.cursor()
            if i.form_submit=='Login':
                check = conn.execute('select * from user_details where username=?and password=?', (i.username, i.password))
                n=check.fetchall()
                if len(n)!=0:
                        session.loggedin = True
                        session.username = i.username
            return render.home('Home')
                else: return render.display('Wrong username or password !')

I want to get the username in some other class. I tried to access the username with session.username , but it shows the following error. AttributeError: 'ThreadedDict' object has no attribute 'username'

回答1:

Just provide the default values for loggedin and username in session's initializer dict. The error seems to appear when those attributes are not set (i.e. when user isn't logged in) and you try to access them.



回答2:

I have made the following changes in my main.py program.

Changes made : Instead of just giving

session = web.session.Session(app,store,initializer={'login': 0,'privilege': 0,'user':'anonymous','loggedin':False}) 

I added following lines of code,

if web.config.get('_session') is None:
    session = web.session.Session(app,store,initializer={'login': 0,'privilege': 0,'user':'anonymous','loggedin':False})
    web.config._session = session
else:
    session = web.config._session

I also made a small change in initilizer dictionary, inititialized user as anonymous and loggedin as false. Thanks to Andrey for giving me the thread.