vendredi 1 novembre 2019

Web.session.Session doesn't seem to store the values through the session

For my project, I need to build a web using python and keep trak of some information and associate it with the user’s browser. I'm using the library web.py, and web.session.Session() to keep trak of information through the browser when refreshing, or redirecting the page using web.seeother('/').

I followed the examples posted in the documentation: example count and example login but they don't seem to work. It looks like the variable session is being reinitialized every time I refresh the browser, or web.seeother('/') is activated.

On this first example, going to the browser shows the value of session.count to 1, and refreshing the page shows the value 2 everytime (I'm expecting to keep increasing this value).

import web

web.config.debug = False

urls = (
    "/count", "count",
    "/reset", "reset",
)

app = web.application(urls, locals())

# Store session data in folder 'sessions' under the same directory as your app.
session = web.session.Session(app, web.session.DiskStore("sessions"), initializer={"count": 0})

class count:
    def GET(self):
        session.count += 1
        return str(session.count)

class reset:
    def GET(self):
        session.kill()
        return "Reset"

if __name__ == "__main__":
    app.run()

On this second example, clicking the link "Login now" does not change the browser, so you're never logged in.

import web


urls = (
    '/', 'Index',
    '/login', 'Login',
    '/logout', 'Logout',
)

web.config.debug = False
app = web.application(urls, locals())
session = web.session.Session(app, web.session.DiskStore('sessions'))      

class Index:
    def GET(self):
        if session.get('logged_in', False):
            return '<h1>You are logged in</h1><a href="/logout">Logout</a>'
        return '<h1>You are not logged in.</h1><a href="/login">Login now</a>'

class Login:
    def GET(self):
        session.logged_in = True
        raise web.seeother('/')

class Logout:
    def GET(self):
        session.logged_in = False
        raise web.seeother('/')


if __name__ == '__main__':
    app.run()

Everything points that the information is not storing properly, or the values are being initialized again, or i didn't undestand how sessions work.

I'm using python 3.7.2 on windows 10.

Any ideas?




Aucun commentaire:

Enregistrer un commentaire