开发者

session in webpy - getting username in all classes

开发者 https://www.devze.com 2023-04-04 17:08 出处:网络
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

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 us开发者_StackOverflow中文版er 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'


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号