Completely solve the problem of saving session in file mode of webpy framework on SAE

2882 단어
1, Solve the errors in the official sae sample code

#app = web.application(urls, globals()).wsgifunc()
app = web.application(urls, globals())

#application = sae.create_wsgi_app(app)
application = sae.create_wsgi_app(app.wsgifunc())


Commenting out the code is the sample code provided by the official, but the official code directly calls wsgifunc() when the APP is instantiated for convenience, but this will cause the calling error of some webpy attributes. For example, the failure of calling app.add_processor.

2, set the call of the global session

# session , session web.config
if web.config.get('_session') is None:
    shop_session = web.session.Session(app, DiskStore(session_root), 
                        initializer={'login_shop_id':'NULL'})
    web.config._session = shop_session
else:
    shop_session = web.config._session
    
def session_hook():
    web.ctx.session = shop_session
    
app.add_processor(web.loadhook(session_hook))
3. Solve the problem that the local directory cannot be read and written in the sae environment

In the SAE environment, python cannot read and write to the local directory, but sae provides Storage, and Storage can be mounted and used like a local disk. So add the following code:

monkey.patch_all()
session_root = '/s/session/'
Note: Storage needs to be enabled in sae in advance, and add "
domain: session"in order to have permissions.


4, Solve the problem that SEA's Storage is mounted as a disk but does not support the os.remove method
"The currently supported (patch) file system interface functions are: open, os.listdir, os.mkdir, os.path.exists, os.path.isdir, os.open, os.fdopen, os.close, os.chmod , os.stat, os.unlink, os.rmdir"but webpy calls os.remove in the DiskStore.cleanup method, which needs to be changed to os.unlink

# SAE stroge os.remove , 
class DiskStore(web.session.DiskStore):
    def __init__(self, root):
        web.session.DiskStore.__init__(self, root)
        # if the storage root doesn't exists, create it.
        # self.root = root
    
    def __delitem__(self, key):
        path = self._get_path(key)
        if os.path.exists(path):
            os.unlink(path)
    
    def cleanup(self, timeout):
        now = time.time()
        for f in os.listdir(self.root):
            path = self._get_path(f)
            atime = os.stat(path).st_atime
            if now - atime > timeout :
                os.unlink(path)# unlink 

OK, now the session can be used normally.


editor by [email protected] Welcome to reprint, please indicate the source

좋은 웹페이지 즐겨찾기