Using beaker
in your bottle
application is easy. First, set up your Bottle app:
import bottle
from bottle import request, route, hook
import beaker.middleware
session_opts = {
'session.type': 'file',
'session.data_dir': './session/',
'session.auto': True,
}
app = beaker.middleware.SessionMiddleware(bottle.app(), session_opts)
And later on:
bottle.run(app=app)
With this in place, every time you receive a request, your Beaker session will be available as
request.environ['beaker_session']
. I usually do something like this for convenience:
@hook('before_request')
def setup_request():
request.session = request.environ['beaker.session']
This arranges to run setup_request
before handling any request; we're using the bottle.request
variable (see the earlier import statement), which is a thread-local variable with information about the current request. From this point on, I can just refer to request.session
whenever I need it, e.g.:
@route('/')
def index():
if 'something' in request.session:
return 'It worked!'
request.session['something'] = 1
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…