我試圖設置裝飾CherryPy控制器類中方法的簡單方法,以便用戶在未經過身份驗證的情況下重定向到登錄頁面。我打算做一個基本的Python裝飾器,但an answer here建議我改用CherryPy自定義工具。所以我試圖做到這一點,但我無法實現它的工作。下面是我有:用於用戶認證的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方法我的自定義工具裝飾,我得到這個錯誤:
AttributeError: 'module' object has no attribute 'session'
然後,當我重新載入頁面,我得到這個錯誤:
AttributeError: '_Serving' object has no attribute 'session'
編輯:甚至想在我的控制器類這麼多,我仍然得到「模塊對象沒有屬性會話」的錯誤:
class Root(BaseModule):
_cp_config = {'tools.sessions.on': True}
sess = cherrypy.session # Error here
...
他們,雖然。 :(更新了顯示我的會話設置的問題,我正在查看你的教程#7鏈接。 –