0

I want to build a web application and also understand the technology in the process. I chose python Bottle for my framework. To implement users on the website, I need to manage sessions. Is there an "easy" or "simple" way to implement sessions in python? I don't care about doing this 100% right. I just want to understand what's going on.

The Bottle documentation suggests I use another library, but I don't like that because it adds more blackboxes (reading the source is an eventual goal...).

I've google searched "implementing sessions python". I just found this.

  • Not really. You can try to implement the sessionmiddleware api yourself. Or you can use beaker. – pvg Jan 13 '16 at 18:04
  • he is asking how to implement it ... all sessions are is user data, that presents more security than standard cookies ... – Joran Beasley Jan 13 '16 at 18:15

1 Answers1

0

python has really nothing to do with it just look into "implement session data" .... here is one way to implement sessions ...

from pyDES import * # or some other crypto library
my_app_secret = "hello crypto"


def save_session(data):
    response.set_cookie("session", triple_des(my_app_secret).encrypt(json.dumps(data), padmode=2))

def load_session():
     try:
        return json.loads(triple_des(my_app_secret).decrypt(response.get_cookie("session"))
      except:
         return {}


 session_data = load_session()
 print session_data
 session_data["some_info"] = "Yellow Submarine"
 save_session(session_data)

alternatively you could save to a database and just save a hash identifier in the cookie ... or various other methods ... (you dont even really need to encrypt it... you could have something as simple as adding a checksum byte to the end of the datastring or something)

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
  • is it common practice (is it safe?) to write the key for the encryption in the code? – isthisreallife Jan 13 '16 at 19:24
  • you could keep it anywhere you want (environment variable... different config file ... command line arguments ... ) I think in most instances people do just include it ...(just dont post it on github if you do) – Joran Beasley Jan 13 '16 at 19:46
  • suppose that the only thing i want from my session is to keep track of logged in users. is the message i save to my session cookie arbitrary? what should be saved? thanks a lot by the way – isthisreallife Jan 13 '16 at 21:39
  • save whatever you want ... often time something simple like `session['logged_in']=True` is sufficient – Joran Beasley Jan 13 '16 at 21:45
  • and you used json as opposed to pickling because pickling is riskier? – isthisreallife Jan 13 '16 at 22:28
  • actually it was fairly arbitrary ... but now that you mention it yes, pickle does have some security implications that json does not – Joran Beasley Jan 13 '16 at 22:30