http://webpython.codepoint.net/cgi_session 里提到几种实现session id传递的方法
1) cookie2) 查询字符串 Query String SID3) 隐藏的表格域 Hidden Field SID
这个session的实现, 由应用自行选择session的生成与传递, 不会依赖于cookie
可用于webpy, bottle等wsgi框架
simplesession.py
#!/usr/bin/env python# -*- coding: utf-8 -*-import pickleimport osimport tracebackimport timeclass Session(dict): session_path = '/dev/shm/sessions' session_file = '' def __init__(self, sessionid): self.session_file = self.session_path + '/' + sessionid try: #Load the session variables from file with open(self.session_file, 'rb') as fp: session_data = pickle.load(fp) self.update(session_data) except (KeyboardInterrupt, SystemExit): raise except: traceback.print_exc() #If the file doesn't exist, continue with a blank session. pass def save(self): #save the session variables back to file if not os.path.exists(self.session_path): os.makedirs() os.chmod(self.session_path, 0660) session_data = dict(self.items()) with open(self.session_file, 'wb') as fp: pickle.dump(session_data, fp) def delete(self): self.clear() try: os.remove(self.session_file) except: traceback.print_exc() pass def cleanup(self, timeout): now = time.time() for f in os.listdir(self.session_path): path = os.path.join(self.session_path, f) atime = os.stat(path).st_atime if now - atime > timeout : os.remove(path)
testhttpserver.py
import webfrom simplesession import Sessionurls = ( "/count", "count",)app = web.application(urls, locals())class count: def GET(self): session = Session('5aa51234') try: count = session['count'] except KeyError: count = 1 count = count + 1 session['count'] = count session.save() return str(count)if __name__ == "__main__": app.run()
对于特定的手机应用, session在post数据里,要应用自己取出来
原文地址:一个不依赖于cookie的session实现, 感谢原作者分享。 对的,坚持;错的,放弃!