SoFunction
Updated on 2024-12-12

Using beaker to get Facebook's Bottle framework to support session functionality

Bottle is a small web framework , very small only one file , but the function is very powerful , learning is also simple , simple and compact at the same time there are many shortcomings , some functional support is not very perfect , such as session. but also has its own benefits, we can own or use other modules to extend it , unlike django, very powerful, but want to further expand the when you want to extend it further . We can put a very simple but powerful bottle do it yourself to become more powerful and perfect.

Bottle compact support cookie but not support session. For security reasons we sometimes want to use session. We can use the middleware beaker to extend the bottle, so that our bottle application supports session. First of all, beaker is not a built-in module, we first install it. Of course, you can install it manually by downloading the package online, but we will use the simplest one.

easy_install beaker

There is no easy_install command? Google it, after installing it, it is still not there. If you have outdated Win, check the environment variables and add the Scripts directory in the Python installation directory to the environment variables.

Once installed, how do we use it? The following paragraph shows how to use it.

#!/usr/bin/env python
from bottle import route, default_app, run, request
from  import SessionMiddleware

session_opts = {
        '':'file',
        'session.cookei_expires':300,
        'session.data_dir':'./sessions',
        '':True
        }

@route('/test')
def test():
  s = ('')
  s['test'] = ('test', 0) + 1
  ()
  return 'Test conter: %d' % s['test']

app = default_app()
app = SessionMiddleware(app, session_opts)
run(app=app)

Run this code, and you will be prompted.

Bottle server starting up (using WSGIRefServer())...
Listening on http://127.0.0.1:8080/
Hit Ctrl-C to quit.

Now open your browser and visit http://127.0.0.1:8080/test

Keep refreshing and you will see that the value is increasing. This means that our session is working properly