Example #1
0
    def clear(self):
        """
        Removes session data items, doesn't delete the session. It does work
        with cookie sessions, and must be called before any output is sent
        to the browser, as it set cookies.

        Returns True
        """
        sessiondata = self._get()
        # delete from datastore
        if sessiondata is not None:
            for sd in sessiondata:
                sd.delete()
        # delete from memcache
        self.cache = {}
        self.cookie_vals = {}
        self.output_cookie["%s_data" % (self.cookie_name)] = \
            simplejson.dumps(self.cookie_vals)
        self.output_cookie["%s_data" % (self.cookie_name)]["path"] = \
            self.cookie_path
        if self.cookie_domain:
            self.output_cookie["%s_data" % \
                (self.cookie_name)]["domain"] = self.cookie_domain
        # Delete the "_data" cookie in the browser
        self.output_cookie["%s_data" % (self.cookie_name)]["expires"] = 0

        print self.output_cookie.output()
        return True
Example #2
0
    def _delete_session(self):
        """
        private method
        
        Delete the session and all session data.

        Returns True.
        """
        # if the event class has been loaded, fire off the preSessionDelete event
        if u"AEU_Events" in sys.modules['__main__'].__dict__:
            sys.modules['__main__'].AEU_Events.fire_event(u"preSessionDelete")
        if hasattr(self, u"session"):
            self.session.delete()
        self.cookie_vals = {}
        self.cache = {}
        self.output_cookie["%s_data" % (self.cookie_name)] = \
            simplejson.dumps(self.cookie_vals)
        self.output_cookie["%s_data" % (self.cookie_name)]["path"] = \
            self.cookie_path
        if self.cookie_domain:
            self.output_cookie["%s_data" % \
                (self.cookie_name)]["domain"] = self.cookie_domain
        # Delete the cookies (session & data) in the browser
        self.output_cookie[self.cookie_name]["expires"] = 0
        self.output_cookie["%s_data" % (self.cookie_name)]["expires"] = 0

        print self.output_cookie.output()
        # if the event class has been loaded, fire off the sessionDelete event
        if u"AEU_Events" in sys.modules['__main__'].__dict__:
            sys.modules['__main__'].AEU_Events.fire_event(u"sessionDelete")
        return True
Example #3
0
    def put(self, keyname, value, session):
        """
        Insert a keyname/value pair into the datastore for the session.

        Args:
            keyname: The keyname of the mapping.
            value: The value of the mapping.

        Returns True
        """
        keyname = session._validate_key(keyname)
        if value is None:
            raise ValueError(u"You must pass a value to put.")

        # Use simplejson for cookies instead of pickle.
        session.cookie_vals[keyname] = value
        # update the requests session cache as well.
        session.cache[keyname] = value
        # simplejson will raise any error I'd raise about an invalid value
        # so let it raise exceptions
        session.output_cookie["%s_data" % (session.cookie_name)] = \
            simplejson.dumps(session.cookie_vals)
        session.output_cookie["%s_data" % (session.cookie_name)]["path"] = \
            session.cookie_path
        if session.cookie_domain:
            session.output_cookie["%s_data" % \
                (session.cookie_name)]["domain"] = session.cookie_domain
        print session.output_cookie.output()
        return True
Example #4
0
    def __delitem__(self, keyname):
        """
        Delete item from session data.

        Args:
            keyname: The keyname of the object to delete.
        """
        bad_key = False
        sessdata = self._get(keyname = keyname)
        if sessdata is None:
            bad_key = True
        else:
            sessdata.delete()
        if keyname in self.cookie_vals:
            del self.cookie_vals[keyname]
            bad_key = False
            self.output_cookie["%s_data" % (self.cookie_name)] = \
                simplejson.dumps(self.cookie_vals)
            self.output_cookie["%s_data" % (self.cookie_name)]["path"] = \
                self.cookie_path
            if self.cookie_domain:
                self.output_cookie["%s_data" % \
                    (self.cookie_name)]["domain"] = self.cookie_domain

            print self.output_cookie.output()
        if bad_key:
            raise KeyError(unicode(keyname))
        if keyname in self.cache:
            del self.cache[keyname]
Example #5
0
    def _log_error(self):
        exc_type, value, tb = sys.exc_info()
        tblist = traceback.extract_tb(tb)
        message = traceback.format_list(tblist)
        del message[:2]
        if message:
            # we don't print the 'Traceback...' part for SyntaxError
            message.insert(0, "Traceback (most recent call last):\n")

        message.extend(traceback.format_exception_only(exc_type, value))
        raise CustomJsException("console.warn(%s)" % dumps(''.join(message)))
Example #6
0
    def put(self, keyname, value, session):
        """
        Insert a keyname/value pair into the datastore for the session.

        Args:
            keyname: The keyname of the mapping.
            value: The value of the mapping.

        Returns the model entity key
        """
        keyname = session._validate_key(keyname)
        if value is None:
            raise ValueError(u"You must pass a value to put.")

        # datestore write trumps cookie. If there is a cookie value
        # with this keyname, delete it so we don't have conflicting
        # entries.
        if session.cookie_vals.has_key(keyname):
            del(session.cookie_vals[keyname])
            session.output_cookie["%s_data" % (session.cookie_name)] = \
                simplejson.dumps(session.cookie_vals)
            session.output_cookie["%s_data" % (session.cookie_name)]["path"] = \
                session.cookie_path
            if session.cookie_domain:
                session.output_cookie["%s_data" % \
                    (session.cookie_name)]["domain"] = session.cookie_domain
            print session.output_cookie.output()

        sessdata = session._get(keyname = keyname)
        if sessdata is None:
            sessdata = _AppEngineUtilities_SessionData()
            # sessdata.session_key = session.session.key()
            sessdata.keyname = keyname
        try:
            db.model_to_protobuf(value)
            if not value.is_saved():
                value.put()
            sessdata.model = value
        except:
            sessdata.content = pickle.dumps(value)
            sessdata.model = None
        sessdata.session = session.session

        session.cache[keyname] = value
        return sessdata.put()
Example #7
0
 def to_js(self):
     """
     generates js for now it only allows str
     """
     return dumps(self.value)
Example #8
0
def get_js(result):
    global MESSAGES
    if not MESSAGES: return
    m = '\n'.join(MESSAGES)
    MESSAGES = []
    return "function(){console.log(%s);return %s;}()" % (dumps(m), result)
Example #9
0
    def __init__(self, cookie_path = SESSION_SETTINGS["DEFAULT_COOKIE_PATH"],
            cookie_domain = SESSION_SETTINGS["DEFAULT_COOKIE_DOMAIN"],
            cookie_name = SESSION_SETTINGS["COOKIE_NAME"],
            session_expire_time = SESSION_SETTINGS["SESSION_EXPIRE_TIME"],
            clean_check_percent = SESSION_SETTINGS["CLEAN_CHECK_PERCENT"],
            integrate_flash = SESSION_SETTINGS["INTEGRATE_FLASH"],
            check_ip = SESSION_SETTINGS["CHECK_IP"],
            check_user_agent = SESSION_SETTINGS["CHECK_USER_AGENT"],
            set_cookie_expires = SESSION_SETTINGS["SET_COOKIE_EXPIRES"],
            session_token_ttl = SESSION_SETTINGS["SESSION_TOKEN_TTL"],
            last_activity_update = SESSION_SETTINGS["UPDATE_LAST_ACTIVITY"],
            writer = SESSION_SETTINGS["WRITER"]):
        """
        Initializer

        Args:
          cookie_path: The path setting for the cookie.
          cookie_domain: The domain setting for the cookie. (Set to False
                        to not use)
          cookie_name: The name for the session cookie stored in the browser.
          session_expire_time: The amount of time between requests before the
              session expires.
          clean_check_percent: The percentage of requests the will fire off a
              cleaning routine that deletes stale session data.
          integrate_flash: If appengine-utilities flash utility should be
              integrated into the session object.
          check_ip: If browser IP should be used for session validation
          check_user_agent: If the browser user agent should be used for
              sessoin validation.
          set_cookie_expires: True adds an expires field to the cookie so
              it saves even if the browser is closed.
          session_token_ttl: Number of sessions a session token is valid
              for before it should be regenerated.
        """

        self.cookie_path = cookie_path
        self.cookie_domain = cookie_domain
        self.cookie_name = cookie_name
        self.session_expire_time = session_expire_time
        self.integrate_flash = integrate_flash
        self.check_user_agent = check_user_agent
        self.check_ip = check_ip
        self.set_cookie_expires = set_cookie_expires
        self.session_token_ttl = session_token_ttl
        self.last_activity_update = last_activity_update
        self.writer = writer

        # make sure the page is not cached in the browser
        print self.no_cache_headers()
        # Check the cookie and, if necessary, create a new one.
        self.cache = {}
        string_cookie = os.environ.get(u"HTTP_COOKIE", u"")
        self.cookie = Cookie.SimpleCookie()
        self.output_cookie = Cookie.SimpleCookie()
        if string_cookie == "":
            self.cookie_vals = {}
        else:
            self.cookie.load(string_cookie)
            try:
                self.cookie_vals = \
                    simplejson.loads(self.cookie["%s_data" % (self.cookie_name)].value)
                    # sync self.cache and self.cookie_vals which will make those
                    # values available for all gets immediately.
                for k in self.cookie_vals:
                    self.cache[k] = self.cookie_vals[k]
                    # sync the input cookie with the output cookie
                    self.output_cookie["%s_data" % (self.cookie_name)] = \
                        simplejson.dumps(self.cookie_vals) #self.cookie["%s_data" % (self.cookie_name)]
            except Exception, e:
                self.cookie_vals = {}