简体   繁体   中英

Error using session RamSession with cherrypy behind nginx

I am running a cherrypy application using my own session based of RamSession behind nginx. The problem is the session id changes on every request. I believe the problem is every time a request is made it goes to a different worker and thus the session is saved, but it is not recognized in the next request by the next available worker (limited knowledge on how things work unfortunately). When I set the number of workers to 1 then everything works as expected. I know I can probably use FileSession or any type of DB based session handler, but just wanted to know if there is a solution for this. Thanks

Here is my upstart script:

description "uwsgi tiny instance"
start on runlevel [12345]
stop on runlevel [06]

exec /home/web/.virtualenvs/myenv/bin/uwsgi --uid web -H /home/web/.virtualenvs/myenv -w myapp.wsgi -p 1 -M -s 127.0.0.1:3031

Here is my session:

class MySession(sessions.RamSession):
    def clean_up(self):
        """Clean up expired sessions."""
        now = self.now()
        for id, (data, expiration_time) in copyitems(self.cache):
            if expiration_time <= now:
                try:
                    active = Mongo(ActiveSession).find_one('active', self.cache['active'])
                    Mongo(ActiveSession).remove(active)
                except:
                    print "Failed to remove active session object."
                try:
                    del self.cache[id]
                except KeyError:
                    pass
                try:
                    del self.locks[id]
                except KeyError:
                    pass
        # added to remove obsolete lock objects
        for id in list(self.locks):
            if id not in self.cache:
                self.locks.pop(id, None)

and my config:

config = {
    '/static': {
        'tools.staticdir.on': True,
        'tools.staticdir.dir': os.path.join(current_dir, 'media/public')
    },
    '/fotos': {
        'tools.staticdir.on': True,
        'tools.staticdir.dir': os.path.join(current_dir, 'media/fotos')
    },
    '/' : {
        'tools.sessions.on': True,
        'tools.sessions.name': 'myapp'
        'tools.sessions.storage_type': 'my',
        'engine.autoreload_on': False
    }
}

Your intuition is correct: the RamSession is limited to 1 process at a time. The simple solution would be to switch to FileSession (if your workers all have access to the same filesystem) or a DB session. Assuming your workers are heavily distributed, most likely the latter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM