1
我是一个刚刚开始使用Python的PHP程序员。我试图让Python通过数据库存储的会话来处理登录/注销。事情有效,但似乎不一致。例如,有时用户没有注销。有时用户“切换”登录。我猜这与线程安全有关,但我不确定从哪里开始解决这个问题。任何帮助,将不胜感激。这是我现在有:正确的方法来做一个PHP程序员的Python + Pylons会话处理
#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
然后我就可以从我的控制器访问用户{}全球:
#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'
有没有更好的方式来做到这一点?谢谢你的帮助。
我还没有与主塔会话,所以我没有任何帮助。但是,由于您刚开始使用Python,我可能会建议像这样重构验证函数:if not user.get('authenticated',False):redirect(blah blah),这样就不必捕获KeyError例外。 – 2010-10-06 17:04:37
谢谢。我现在将执行此操作。 – ensnare 2010-10-11 17:31:57