python类session()的实例源码

sessions.py 文件源码 项目:autosub-bootstrapbill 作者: BenjV 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def __init__(self, id=None, **kwargs):
        self.id_observers = []
        self._data = {}

        for k, v in kwargs.items():
            setattr(self, k, v)

        self.originalid = id
        self.missing = False
        if id is None:
            if self.debug:
                cherrypy.log('No id given; making a new one', 'TOOLS.SESSIONS')
            self._regenerate()
        else:
            self.id = id
            if self._exists():
                if self.debug:
                    cherrypy.log('Set id to %s.' % id, 'TOOLS.SESSIONS')
            else:
                if self.debug:
                    cherrypy.log('Expired or malicious session %r; '
                                 'making a new one' % id, 'TOOLS.SESSIONS')
                # Expired or malicious session. Make a new one.
                # See https://github.com/cherrypy/cherrypy/issues/709.
                self.id = None
                self.missing = True
                self._regenerate()
sessions.py 文件源码 项目:autosub-bootstrapbill 作者: BenjV 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def now(self):
        """Generate the session specific concept of 'now'.

        Other session providers can override this to use alternative,
        possibly timezone aware, versions of 'now'.
        """
        return datetime.datetime.now()
sessions.py 文件源码 项目:autosub-bootstrapbill 作者: BenjV 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def regenerate(self):
        """Replace the current session (with a new id)."""
        self.regenerated = True
        self._regenerate()
sessions.py 文件源码 项目:autosub-bootstrapbill 作者: BenjV 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _regenerate(self):
        if self.id is not None:
            if self.debug:
                cherrypy.log(
                    'Deleting the existing session %r before '
                    'regeneration.' % self.id,
                    'TOOLS.SESSIONS')
            self.delete()

        old_session_was_locked = self.locked
        if old_session_was_locked:
            self.release_lock()
            if self.debug:
                cherrypy.log('Old lock released.', 'TOOLS.SESSIONS')

        self.id = None
        while self.id is None:
            self.id = self.generate_id()
            # Assert that the generated id is not already stored.
            if self._exists():
                self.id = None
        if self.debug:
            cherrypy.log('Set id to generated %s.' % self.id,
                         'TOOLS.SESSIONS')

        if old_session_was_locked:
            self.acquire_lock()
            if self.debug:
                cherrypy.log('Regenerated lock acquired.', 'TOOLS.SESSIONS')
sessions.py 文件源码 项目:autosub-bootstrapbill 作者: BenjV 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def generate_id(self):
        """Return a new session id."""
        return random20()
sessions.py 文件源码 项目:autosub-bootstrapbill 作者: BenjV 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def load(self):
        """Copy stored session data into this session instance."""
        data = self._load()
        # data is either None or a tuple (session_data, expiration_time)
        if data is None or data[1] < self.now():
            if self.debug:
                cherrypy.log('Expired session %r, flushing data.' % self.id,
                             'TOOLS.SESSIONS')
            self._data = {}
        else:
            if self.debug:
                cherrypy.log('Data loaded for session %r.' % self.id,
                             'TOOLS.SESSIONS')
            self._data = data[0]
        self.loaded = True

        # Stick the clean_thread in the class, not the instance.
        # The instances are created and destroyed per-request.
        cls = self.__class__
        if self.clean_freq and not cls.clean_thread:
            # clean_up is an instancemethod and not a classmethod,
            # so that tool config can be accessed inside the method.
            t = cherrypy.process.plugins.Monitor(
                cherrypy.engine, self.clean_up, self.clean_freq * 60,
                name='Session cleanup')
            t.subscribe()
            cls.clean_thread = t
            t.start()
            if self.debug:
                cherrypy.log('Started cleanup thread.', 'TOOLS.SESSIONS')
sessions.py 文件源码 项目:autosub-bootstrapbill 作者: BenjV 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def delete(self):
        """Delete stored session data."""
        self._delete()
        if self.debug:
            cherrypy.log('Deleted session %s.' % self.id,
                         'TOOLS.SESSIONS')

    # -------------------- Application accessor methods -------------------- #
sessions.py 文件源码 项目:autosub-bootstrapbill 作者: BenjV 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def acquire_lock(self):
        """Acquire an exclusive lock on the currently-loaded session data."""
        self.locked = True
        self.locks.setdefault(self.id, threading.RLock()).acquire()
sessions.py 文件源码 项目:autosub-bootstrapbill 作者: BenjV 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def release_lock(self):
        """Release the lock on the currently-loaded session data."""
        self.locks[self.id].release()
        self.locked = False
sessions.py 文件源码 项目:autosub-bootstrapbill 作者: BenjV 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def _get_file_path(self):
        f = os.path.join(self.storage_path, self.SESSION_PREFIX + self.id)
        if not os.path.abspath(f).startswith(self.storage_path):
            raise cherrypy.HTTPError(400, 'Invalid session id in cookie.')
        return f
sessions.py 文件源码 项目:autosub-bootstrapbill 作者: BenjV 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _save(self, expiration_time):
        assert self.locked, ('The session was saved without being locked.  '
                             "Check your tools' priority levels.")
        f = open(self._get_file_path(), 'wb')
        try:
            pickle.dump((self._data, expiration_time), f, self.pickle_protocol)
        finally:
            f.close()
sessions.py 文件源码 项目:autosub-bootstrapbill 作者: BenjV 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _delete(self):
        assert self.locked, ('The session deletion without being locked.  '
                             "Check your tools' priority levels.")
        try:
            os.unlink(self._get_file_path())
        except OSError:
            pass
sessions.py 文件源码 项目:autosub-bootstrapbill 作者: BenjV 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def release_lock(self, path=None):
        """Release the lock on the currently-loaded session data."""
        self.lock.release()
        self.lock.remove()
        self.locked = False
sessions.py 文件源码 项目:autosub-bootstrapbill 作者: BenjV 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def clean_up(self):
        """Clean up expired sessions."""
        now = self.now()
        # Iterate over all session files in self.storage_path
        for fname in os.listdir(self.storage_path):
            if (fname.startswith(self.SESSION_PREFIX)
                    and not fname.endswith(self.LOCK_SUFFIX)):
                # We have a session file: lock and load it and check
                #   if it's expired. If it fails, nevermind.
                path = os.path.join(self.storage_path, fname)
                self.acquire_lock(path)
                if self.debug:
                    # This is a bit of a hack, since we're calling clean_up
                    # on the first instance rather than the entire class,
                    # so depending on whether you have "debug" set on the
                    # path of the first session called, this may not run.
                    cherrypy.log('Cleanup lock acquired.', 'TOOLS.SESSIONS')

                try:
                    contents = self._load(path)
                    # _load returns None on IOError
                    if contents is not None:
                        data, expiration_time = contents
                        if expiration_time < now:
                            # Session expired: deleting it
                            os.unlink(path)
                finally:
                    self.release_lock(path)
sessions.py 文件源码 项目:autosub-bootstrapbill 作者: BenjV 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def release_lock(self):
        """Release the lock on the currently-loaded session data."""
        self.locks[self.id].release()
        self.locked = False
sessions.py 文件源码 项目:autosub-bootstrapbill 作者: BenjV 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def close():
    """Close the session object for this request."""
    sess = getattr(cherrypy.serving, 'session', None)
    if getattr(sess, 'locked', False):
        # If the session is still locked we release the lock
        sess.release_lock()
        if sess.debug:
            cherrypy.log('Lock released on close.', 'TOOLS.SESSIONS')
sessions.py 文件源码 项目:autosub-bootstrapbill 作者: BenjV 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def expire():
    """Expire the current session cookie."""
    name = cherrypy.serving.request.config.get(
        'tools.sessions.name', 'session_id')
    one_year = 60 * 60 * 24 * 365
    e = time.time() - one_year
    cherrypy.serving.response.cookie[name]['expires'] = httputil.HTTPDate(e)
cptools.py 文件源码 项目:autosub-bootstrapbill 作者: BenjV 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def do_logout(self, from_page='..', **kwargs):
        """Logout. May raise redirect, or return True if request handled."""
        sess = cherrypy.session
        username = sess.get(self.session_key)
        sess[self.session_key] = None
        if username:
            cherrypy.serving.request.login = None
            self.on_logout(username)
        raise cherrypy.HTTPRedirect(from_page)
server.py 文件源码 项目:radio-server 作者: ernitron 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def validate_password(self, login, password):
    if login in users :
        if encrypt(password) == users[login] :
            cherrypy.session['username'] = login
            cherrypy.session['database'] = userdatabase(login)
            return True

    return False
server.py 文件源码 项目:radio-server 作者: ernitron 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def haddfav(self, id=""):
        if id == "" or id == None :
          html += "Error missing id"
          return html

        if id == "0" :
          html += "0 is reserved, sorry"
          return html

        (name, genre, url) = getradio(id)
        if 'Fav' in genre:
            genre = genre.replace(', Fav', '')
            star = False
        else:
            genre += ', Fav'
            star = True

        if addgen(id, genre) == False:
            return ''

        (name, genre, url) = getradio(id)
        cherrypy.session['playing'] = id
        html = '<h3>Now Playing: '
        html += '''<a href="%s">%s</a>''' % (url, name)
        html += '''<a href="#" onClick="fplayradio('%s')">''' % url
        html += '''<span class="glyphicon glyphicon-play"></span></a>'''
        html += '''&nbsp;<a href="#" onClick="fmodradio('%s')"><span class="glyphicon glyphicon-pencil"></span></a></small>&nbsp;''' % id
        html += '''<a href="#" onClick="fdelradio('%s')"><span class="glyphicon glyphicon-trash"></span></a>&nbsp;''' % id
        html += '''<a href="#" onClick="faddfav('%s')"><span class="glyphicon glyphicon-star"></span></a>''' % id
        if star:
            html += '''Starred'''
        html += '''</h3>'''

        return html


问题


面经


文章

微信
公众号

扫码关注公众号