GAE Webapp2 - destroying session doesn't work

2019-02-15 08:17发布

问题:

Or do I misunderstand how destroying work? Here's an example code:

class TestHandler(BaseHandler):
    def get(self):
        counter = self.session.get('counter')
        if not counter:
            counter = 0
        counter += 1

        if counter > 5:
            self.auth.unset_session()
        else:
            self.session['counter'] = counter

        return self.response.write ( counter )

Session works, the counter counts, but either session isn't destroyed or destroying it doesn't null the value?

Does destroying null only some values like userid and sessionid or do I completely miss the point? Thanks.

回答1:

unset_session removes the user from the session not the other session variables. The unset_session method is on the auth module.

If you dig a little deeper in the code you can have a look at what the code is doing. http://code.google.com/p/webapp-improved/source/browse/webapp2_extras/auth.py

 def unset_session(self):
        """Removes a user from the session and invalidates the auth token."""
        self._user = None
        data = self.get_session_data(pop=True)
        ....

If you were trying to unset the counter, you could pop the session variable by calling self.session.pop('counter')

For example:

   counter = self.session.get('counter')
    if not counter:
        counter = 0
    counter += 1

    if counter > 5:
        self.session.pop('counter')
    else:
        self.session['counter'] = counter

    return self.response.write ( counter )

If you want to clear everything from the session, you can call self.session.clear()