Proper way to do session handling in Python + Pylons for a php programmer
I'm a php programmer who's just getting started with Python. I'm trying to get Python to handle login/logout via database-stored sessions. Things work, but seem inconsistent. For example, sometimes a user isn't logged out. Sometimes users "switch" logins. I'm guessing this has something to do with thread-safety, but I'm just not sure where to begin on how to fix this. Any help would be appreciated. Here's what I have now:
#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(remo开发者_如何学运维te_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
I can then access the user{} global from my controllers:
#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'
Is there a better way to do this? Thanks for your help.
Pylons has a 'sessions' object that exists to handle this kind of situation. The example on the Pylons website seems to match what you want.
I think you are seeing problems because of the globals 'user' and 'connection'. Pylons has a globals object that is designed to share information between all controllers and is not reset on each request.
精彩评论