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