Bottle.py session with Beaker

后端 未结 1 1905
醉梦人生
醉梦人生 2020-12-13 22:58

first time questioner here.

I\'m currently struggling on how to use Beaker properly using the Bottle micro-framework. Here\'s the problematic program:



        
相关标签:
1条回答
  • 2020-12-13 23:31

    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
    
    0 讨论(0)
提交回复
热议问题