2014-01-20 140 views
0

瓶展示如何使用燒杯會話管理,像下面如何使用燒杯多瓶應用

import bottle 
from beaker.middleware import SessionMiddleware 

session_opts = { 
    'session.type': 'file', 
    'session.cookie_expires': 300, 
    'session.data_dir': './data', 
    'session.auto': True 
} 
app = SessionMiddleware(bottle.app(), session_opts) 

@bottle.route('/test') 
def test(): 
    s = bottle.request.environ.get('beaker.session') 
    s['test'] = s.get('test',0) + 1 
    s.save() 
    return 'Test counter: %d' % s['test'] 

bottle.run(app=app) 

我的問題是文檔,我有多個瓶應用,他們每個人供應虛擬主機(由cherrypy提供支持)。所以我不能使用裝飾「@ bottle.route」,相反,我需要使用裝飾,如「app1.route('/ test')」,「app2.route('/ test')」。

但是,如果我扭曲的應用程序與燒杯中間件,像下面,

app1= Bottle() 
app2= Bottle() 
app1 = SessionMiddleware(app1, session_opts) 
app2 = SessionMiddleware(app2, session_opts) 

當蟒蛇跑到下面,

@app1.route('/test') 
def test(): 
    return 'OK' 

它會報告錯誤,AttributeError的: 'SessionMiddleware' 對象有沒有屬性'路線'

這是肯定的,因爲現在app1實際上是'SessionMiddleware'而不是Bottle應用程序。

如何解決這個問題?

回答

1

稍微深入燒杯源代碼後,終於找到了方法。

使用Decorator這樣:

@app1.wrap_app.route('/test') 
def test(): 
    return 'OK'