用于用户身份验证的 CherryPy 自定义工具

发布于 2024-11-18 03:22:16 字数 2920 浏览 2 评论 0原文

我正在尝试在 CherryPy 控制器类中设置一种简单的装饰方法,以便用户在尚未经过身份验证时被重定向到登录页面。我本来打算做一个基本的Python装饰器,但是这里的答案建议我请改用 CherryPy 自定义工具。所以我正在尝试这样做,但我无法让它发挥作用。这是我所拥有的:

def authenticate():
    user = cherrypy.session.get('user', None)
    if not user:
        raise cherrypy.HTTPRedirect('/?errMsg=Please%20log%20in%20first')

cherrypy.tools.authenticate = cherrypy.Tool('on_start_resource', authenticate)

/home 页面是一个应该仅限于经过身份验证的用户的页面,因此我有以下内容:

@cherrypy.expose
@cherrypy.tools.authenticate
def home(self, **kwargs):
    tmpl = TemplateDir.get_template('home.mako')
    return tmpl.render()

但是,当我尝试启动我的网站时,我收到此错误:

Traceback (most recent call last):
  File ".\example.py", line 3, in <module>
    from controller.main import Root
  File "C:\...\controller\main.py", line 9, in <module>
    class Root(BaseModule):
  File "C:\...\controller\main.py", line 19, in Root
    @cherrypy.tools.authenticate
  File "C:\Python26\lib\site-packages\cherrypy\_cptools.py", line 119, in
   __call__ % self._name)
TypeError: The 'authenticate' Tool does not accept positional arguments; you must
  use keyword arguments.

编辑:好的,如果我将自定义工具的使用更改为带有括号,我会收到不同的错误。

@cherrypy.expose
@cherrypy.tools.authenticate() # Magic parentheses...
def home(self, **kwargs):
    ...

现在我得到:

Traceback (most recent call last):
  File "C:\Python26\lib\site-packages\cherrypy\_cprequest.py", line 625, in respond
    self.hooks.run('on_start_resource')
  File "C:\Python26\lib\site-packages\cherrypy\_cprequest.py", line 97, in run
    hook()
  File "C:\Python26\lib\site-packages\cherrypy\_cprequest.py", line 57, in __call__
    return self.callback(**self.kwargs)
  File ".\example.py", line 40, in authenticate
    user = cherrypy.session.get('user', None)
AttributeError: 'module' object has no attribute 'session'

编辑: 我已打开会话:

cherrypy.tools.sessions.storage_type = 'file'
cherrypy.tools.sessions.storage_path = r'%s\sessions' % curDir
cherrypy.tools.sessions.timeout = 60
cherrypy.tree.mount(Root(), "/", config={
    '/static': {
        'tools.staticdir.on':True,
        'tools.staticdir.dir':r'%s\static' % curDir,
    },
    '/': {
        'tools.sessions.on':True,
    }
})

当我第一次在 Web 方法上使用自定义工具装饰器加载页面时,出现以下错误:

属性错误:“模块”对象没有属性“会话”

然后当我重新加载页面时,出现此错误:

属性错误:“_Serving”对象没有属性“会话”

编辑: 即使在我的控制器类中尝试了这么多,我仍然收到 'module object has no attribute session' 错误:

class Root(BaseModule):
    _cp_config = {'tools.sessions.on': True}
    sess = cherrypy.session # Error here
    ...

I'm trying to set up a simple way of decorating methods in my CherryPy controller classes so that a user is redirected to the login page if they haven't authenticated yet. I was going to do a basic Python decorator, but an answer here suggested I use a CherryPy Custom Tool instead. So I'm trying to do that, but I can't get it to work. Here's what I have:

def authenticate():
    user = cherrypy.session.get('user', None)
    if not user:
        raise cherrypy.HTTPRedirect('/?errMsg=Please%20log%20in%20first')

cherrypy.tools.authenticate = cherrypy.Tool('on_start_resource', authenticate)

The /home page is a page that should be restricted to authenticated users, so I have this:

@cherrypy.expose
@cherrypy.tools.authenticate
def home(self, **kwargs):
    tmpl = TemplateDir.get_template('home.mako')
    return tmpl.render()

However, I get this error when I try to start my web site:

Traceback (most recent call last):
  File ".\example.py", line 3, in <module>
    from controller.main import Root
  File "C:\...\controller\main.py", line 9, in <module>
    class Root(BaseModule):
  File "C:\...\controller\main.py", line 19, in Root
    @cherrypy.tools.authenticate
  File "C:\Python26\lib\site-packages\cherrypy\_cptools.py", line 119, in
   __call__ % self._name)
TypeError: The 'authenticate' Tool does not accept positional arguments; you must
  use keyword arguments.

Edit: okay, if I change my use of the custom tool to have parentheses, I get a different error.

@cherrypy.expose
@cherrypy.tools.authenticate() # Magic parentheses...
def home(self, **kwargs):
    ...

Now I get:

Traceback (most recent call last):
  File "C:\Python26\lib\site-packages\cherrypy\_cprequest.py", line 625, in respond
    self.hooks.run('on_start_resource')
  File "C:\Python26\lib\site-packages\cherrypy\_cprequest.py", line 97, in run
    hook()
  File "C:\Python26\lib\site-packages\cherrypy\_cprequest.py", line 57, in __call__
    return self.callback(**self.kwargs)
  File ".\example.py", line 40, in authenticate
    user = cherrypy.session.get('user', None)
AttributeError: 'module' object has no attribute 'session'

Edit: I have sessions turned on:

cherrypy.tools.sessions.storage_type = 'file'
cherrypy.tools.sessions.storage_path = r'%s\sessions' % curDir
cherrypy.tools.sessions.timeout = 60
cherrypy.tree.mount(Root(), "/", config={
    '/static': {
        'tools.staticdir.on':True,
        'tools.staticdir.dir':r'%s\static' % curDir,
    },
    '/': {
        'tools.sessions.on':True,
    }
})

When I first load the page with my custom tool decorator on the web method, I get this error:

AttributeError: 'module' object has no attribute 'session'

Then when I reload the page, I get this error:

AttributeError: '_Serving' object has no attribute 'session'

Edit: even trying this much in my controller class, I still get the 'module object has no attribute session' error:

class Root(BaseModule):
    _cp_config = {'tools.sessions.on': True}
    sess = cherrypy.session # Error here
    ...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

何处潇湘 2024-11-25 03:22:16

我使用了错误的钩子。更改:

cherrypy.tools.authenticate = cherrypy.Tool('on_start_resource', authenticate)

至:

cherrypy.tools.authenticate = cherrypy.Tool('before_handler', authenticate)

解决了问题。显然,我的 authenticate 方法在会话打开之前被调用,因此它无法访问 cherrypy.session。我的控制器中不需要任何会话开启的东西;所需要的只是我的服务器启动脚本中的以下内容:

def authenticate():
    ...
cherrypy.tools.authenticate = cherrypy.Tool('before_handler', authenticate)
cherrypy.tree.mount(Root(), "/", config={
    "/": {
        'tools.sessions.on':True,
        'tools.sessions.storage_type':'file',
        'tools.sessions.storage_path':r'%s\sessions' % curDir,
        'tools.sessions.timeout':60
    }, ...
})

然后,在我的控制器中的受限方法上:

@cherrypy.expose
@cherrypy.tools.authenticate()
def home(self, **kwargs):
    ...

I was using the wrong hook. Changing:

cherrypy.tools.authenticate = cherrypy.Tool('on_start_resource', authenticate)

To:

cherrypy.tools.authenticate = cherrypy.Tool('before_handler', authenticate)

Fixed the problem. Apparently my authenticate method was getting called before sessions had been turned on, so it couldn't access cherrypy.session. I didn't need any session-turn-on stuff in my controllers; all that was necessary was the following in my server-start script:

def authenticate():
    ...
cherrypy.tools.authenticate = cherrypy.Tool('before_handler', authenticate)
cherrypy.tree.mount(Root(), "/", config={
    "/": {
        'tools.sessions.on':True,
        'tools.sessions.storage_type':'file',
        'tools.sessions.storage_path':r'%s\sessions' % curDir,
        'tools.sessions.timeout':60
    }, ...
})

Then, in my controller on a restricted method:

@cherrypy.expose
@cherrypy.tools.authenticate()
def home(self, **kwargs):
    ...
路弥 2024-11-25 03:22:16

最有可能的是会话未启用。 会话 wiki 页面 上有一个示例配置文件,或者查看 教程#7

Most likely sessions aren't enabled. There's an example config file on the session wiki page, or have a look at tutorial #7.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文