Python + Pylons中会话处理的正确方法(适合PHP程序员)
我是一名刚开始学习Python的PHP程序员。我正在尝试让Python通过数据库存储的会话来处理登录和登出。现在的情况是,虽然有些功能可以正常工作,但有时却不太稳定。例如,有时候用户没有被登出,有时候用户的登录状态会“切换”。我猜这可能和线程安全有关,但我不知道从哪里开始解决这个问题。任何帮助都非常感谢。以下是我现在的代码:
#lib/base.py
def authenticate():
#Confirm login
try:
if user['authenticated'] != True:
redirect_to(controller='login', action='index')
except KeyError:
redirect_to(controller='login', action='index')
#Global variables
user = {}
connection = {}
class BaseController(WSGIController):
#Read if there is a cookie set
try:
session = request.cookies['session']
#Create a session object from the session id
session_logged_in = Session(session)
#If the session is valid, retrieve the user info
if session_logged_in.isValid(remote_addr):
#Set global variables about the logged in user
user_logged_in = User(session_logged_in.user_id)
user['name'] = c.name = user_logged_in.name
user['name_url'] = c.name_url = user_logged_in.name_url
user['first_name'] = c.first_name = user_logged_in.first_name
user['last_name'] = c.last_name = user_logged_in.last_name
user['email'] = c.email = user_logged_in.email
user['about'] = c.about = user_logged_in.about
user['authenticated'] = c.authenticated = True
user['profile_url'] = c.profile_url = user_logged_in.profile_url
user['user_thumb'] = c.user_thumb = user_logged_in.user_thumb
user['image_id'] = c.image_id = user_logged_in.image_id
user['id'] = c.user_id = user_logged_in.id
#Update the session
session_logged_in.current_uri = requested_url
session_logged_in.update()
#If no session has been set, do nothing
except KeyError:
user['authenticated'] = False
我可以从我的控制器中访问user{}这个全局变量:
#controllers/profile.py
from project.lib.base import BaseController, user
class ProfileController(BaseController):
def index(self, id=None, name_url=None):
#If this is you
if user['id'] == 1
print 'this is you'
有没有更好的方法来实现这个功能?谢谢你的帮助。