Python + Pylons中会话处理的正确方法(适合PHP程序员)

1 投票
1 回答
960 浏览
提问于 2025-04-16 05:05

我是一名刚开始学习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'

有没有更好的方法来实现这个功能?谢谢你的帮助。

1 个回答

3

Pylons 有一个叫做 'sessions' 的对象,专门用来处理这种情况。在 Pylons 的网站上,有一个示例,看起来正好符合你的需求。

我觉得你遇到问题是因为全局变量 'user' 和 'connection'。Pylons 有一个globals 对象,旨在让所有控制器之间共享信息,并且在每次请求时不会被重置。

撰写回答