Does Python have a session feature or not?
If it does, then how can I use this and whic开发者_如何学Goh library should I use?
This might be an old question, but I faced the same problem that there is no built-in session support in Python. I wrote a simple session handler that might be useful for someone :
#!/usr/bin/python
# -*- coding: utf-8 -*-
import tempfile
import hashlib
import os
import time
import random
import errno
import ast
import pprint
import fcntl
class CGISession:
__sessionfile = ''
__newid = ''
__date = ''
__tmp = ''
__pid = ''
__time = ''
__rand = ''
__pp = pprint.PrettyPrinter()
__fs = ''
def __init__(
self,
id=None,
directory=None,
hash='md5',
):
if directory is None:
self.__directory = tempfile.gettempdir()
else:
if not os.path.exists(directory):
try:
os.makedirs(directory)
except OSError, error:
if error.errno != errno.EEXIST:
raise
self.__directory = directory
if hash not in ['md5', 'sha256', 'sha512']:
self.__hash = 'md5'
else:
self.__hash = hash
if id is None:
self.__id = self.__genSessionID()
self.__fs = open(os.path.join(self.__directory,
'pycgiession_{0}'.format(self.__id)), 'w')
fcntl.flock(self.__fs.fileno(), fcntl.LOCK_EX)
self.__fs.write('{}')
self.__fs.close()
self.__sessionfile = os.path.join(self.__directory,
'pycgiession_{0}'.format(self.__id))
os.chmod(self.__sessionfile, 0640)
else:
try:
open(os.path.join(self.__directory,
'pycgiession_{0}'.format(os.path.basename(id))),
'r').close()
self.__id = os.path.basename(id)
self.__sessionfile = os.path.join(self.__directory,
'pycgiession_{0}'.format(self.__id))
os.chmod(self.__sessionfile, 0640)
except IOError, error:
if error.errno == errno.ENOENT:
self.__id = self.__genSessionID()
self.__fs = open(os.path.join(self.__directory,
'pycgiession_{0}'.format(self.__id)), 'w')
fcntl.flock(self.__fs.fileno(), fcntl.LOCK_EX)
self.__fs.write('{}')
self.__fs.close()
self.__sessionfile = os.path.join(self.__directory,
'pycgiession_{0}'.format(self.__id))
os.chmod(self.__sessionfile, 0640)
else:
raise
def __genSessionID(self):
self.__pid = str(os.getpid())
self.__time = ''.join(map(str, time.gmtime()[0:]))
self.__rand = str(random.random())
if self.__hash == 'sha256':
sha256 = hashlib.sha256()
sha256.update(self.__pid)
sha256.update(self.__time)
sha256.update(self.__rand)
self.__newid = sha256.hexdigest()
elif self.__hash == 'sha512':
sha512 = hashlib.sha512()
sha512.update(self.__pid)
sha512.update(self.__time)
sha512.update(self.__rand)
self.__newid = sha512.hexdigest()
else:
md5 = hashlib.md5()
md5.update(self.__pid)
md5.update(self.__time)
md5.update(self.__rand)
self.__newid = md5.hexdigest()
return self.__newid
def getID(self):
return self.__id
def setParam(self, key, value):
self.__fs = open(self.__sessionfile, 'r')
fcntl.flock(self.__fs.fileno(), fcntl.LOCK_EX)
self.__date = self.__fs.readlines()
self.__fs.close()
self.__fs = open(self.__sessionfile, 'w')
fcntl.flock(self.__fs.fileno(), fcntl.LOCK_EX)
self.__date = ast.literal_eval(self.__date[0])
self.__date[key] = value
self.__fs.write(self.__pp.pformat(self.__date))
self.__fs.close()
def getParam(self, key):
self.__fs = open(self.__sessionfile, 'r')
fcntl.flock(self.__fs.fileno(), fcntl.LOCK_EX)
self.__date = self.__fs.readline()
self.__fs.close()
self.__date = ast.literal_eval(self.__date)
try:
self.__date = self.__date[key]
return self.__date
except KeyError:
return None
def getAll(self):
self.__fs = open(self.__sessionfile, 'r')
fcntl.flock(self.__fs.fileno(), fcntl.LOCK_EX)
self.__date = self.__fs.readlines()
self.__fs.close()
self.__date = ast.literal_eval(self.__date[0])
return self.__date
def delParam(self, key):
self.__fs = open(self.__sessionfile, 'r')
fcntl.flock(self.__fs.fileno(), fcntl.LOCK_EX)
self.__date = self.__fs.readlines()
self.__fs.close()
self.__fs = open(self.__sessionfile, 'w')
fcntl.flock(self.__fs.fileno(), fcntl.LOCK_EX)
self.__date = ast.literal_eval(self.__date[0])
try:
del self.__date[key]
except KeyError:
pass
self.__fs.write(self.__pp.pformat(self.__date))
self.__fs.close()
def clear(self):
self.__fs = open(self.__sessionfile, 'w')
fcntl.flock(self.__fs.fileno(), fcntl.LOCK_EX)
self.__fs.write('{}')
self.__fs.close()
def delete(self):
os.remove(self.__sessionfile)
Examples :
>>> from CGISession import CGISession
>>> session = CGISession()
>>>
>>> session.getID()
'7e487c3c300126fddbecb37b041d66e3'
>>>
>>> session.setParam('name','A')
>>> session.setParam('friends',['C','D','E'])
>>>
>>> session.getParam('name')
'A'
>>> session.getParam('friends')
['C', 'D', 'E']
>>>
>>> session.delParam('name')
>>> session.delParam('friends')
>>>
>>> session.getParam('name')
>>> session.delParam('friends')
>>>
>>> session.delete()
>>>
Some Python web frameworks do offer the concept of "session". (The language Python itself, of course, has nothing to do with it!-).
For example, Beaker is an excellent lightweight WSGI middleware that supports sessions; since WSGI is generally the best way to connect any Python web framework with any web server, and of course you can always insert WSGI middleware in WSGI transactions, Beaker (like any other WSGI middleware) is very widely applicable.
Beaker is pretty popular for WSGI reliant Python web apps, but you have to understand that Python is an all-purpose programming language, it is not geared 100% toward the web like PHP.
It would also help if you listed more information about the application you need it in.
精彩评论