FOPENP

Python Sessions with Bottle and Beaker

In Python, creating a session is easy, but you need to use the right instruments. In this post I'll use bottle (a WSGI server) and Beaker (a session manager).

First of all I need to clarify what sessions are. A session is a cookie that has a unique value. Each session can have variables on the server side.

This is an example of Python code that increments a counter every time the main web page ("/") is visited.

    1 #!/usr/bin/python3
    2 
    3 import bottle
    4 from beaker.middleware import SessionMiddleware
    5 
    6 sessionOptions = {
    7     'session.type': 'file',
    8     'session.cookie_expires': 86400,  # expires in 1 day
    9     'session.data_dir': './sessions',
   10     'session.auto': True
   11 }
   12 app = SessionMiddleware(bottle.app(), sessionOptions)
   13 
   14 @bottle.route('/')
   15 def index():
   16   s = bottle.request.environ.get('beaker.session')
   17   s['counter'] = s.get('counter', 0) + 1
   18   s.save()
   19   return f"Counter: {s['counter']}"
   20 
   21 bottle.run(app=app, host="127.0.0.1", port=8000)

The script needs to install two libraries at system level (as root). Execute from a shell:

pip3 install bottle
pip3 install Beaker

At line 12 a new instance of Beaker is created. At line 16, you get from the client the session ID. At line 17, gets a counter which increments by 1 at every page refresh.
At line 18 the counter is saved server-side, in form of file hosted in the "sessions" folder (as specified at lines 7 and 9).
The 21st line make start the web server on the 8000 port, and you can navigate into the web site only from the same computer which the server is started.

In order to see the result, you must visit the following web site: http://127.0.0.1:8000/

2023
Dec, 23