如何在CherryPy中注册filterChainProxy?

2024-06-28 20:54:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近读了gregl.Turnquist的《springpython1.1》。学习python上的spring框架。 在学习的过程中,我尝试了书中介绍的几个例子,在第8章“案例研究I-将SpringPython与Web应用程序集成”中遇到了问题

下面是一个错误。我连谷歌都不知道。。 500内部服务器错误

服务器遇到意外情况,无法完成请求。你知道吗

回溯(最近一次调用last):文件“c:\Python27\lib\site packages\cherrypy_cprequest.py文件,第633行self.namespace名称空间(self.config文件)文件“c:\Python27\lib\site packages\cherrypy\lib\副本“,第115行,在调用退出(None,None,None)文件”c:\Python27\lib\site packages\cherrypy”_cptools.py文件“,第446行,在退出中,tool=getattr(self,name)AttributeError:'Toolbox'对象没有属性'filterChainProxy' 由CherryPy 3.2.4提供支持 我发现CherryPy没有filterChainProxy属性cherrypy.工具. 但是,下面main2.py中的示例代码尝试使用“工具.filterChainProxy.on“据我所知,这就是原因。你知道吗

我在google上找不到任何解决这个问题的方法。为什么作者首先使用tools.filterChainProxy?当时支持,现在不赞成了?或者,为什么?我在cherrypy的文档页面上查了一下,仍然没有任何线索。你知道吗

请帮助我完成下面的代码(我将相关部分放在粗体): 你知道吗

import cherrypy
import os
from springpython.context import ApplicationContext
from springpython.security.context import *

from ctx2 import *

if __name__ == '__main__':
cherrypy.config.update({'server.socket_port': 8009})

ctx = ApplicationContext(SpringBankAppContext())

SecurityContextHolder.setStrategy(SecurityContextH older.MODE_GLOBAL)
SecurityContextHolder.getContext()

conf = {"/": {"tools.sessions.on":True,
**"tools.filterChainProxy.on":True}**}

cherrypy.tree.mount(
ctx.get_object("view"),
'/',
config=conf)

cherrypy.engine.start()
cherrypy.engine.block()

from springpython.config import PythonConfig, Object
from springpython.security.providers import *
from springpython.security.providers.dao import *
from springpython.security.userdetails import *
from springpython.security.vote import *
from springpython.security.web import *
from springpython.security.cherrypy3 import *

from app2 import *

class SpringBankAppContext(PythonConfig):
def __init__(self):
PythonConfig.__init__(self)

@Object
def view(self):
view = SpringBankView()
view.auth_provider = self.auth_provider()
view.filter = self.auth_processing_filter()
view.http_context_filter = self.httpSessionContextIntegrationFilter()
return view

@Object
def **filterChainProxy**(self):
return CP3FilterChainProxy(filterInvocationDefinitionSour ce = 
[
("/login.*", ["httpSessionContextIntegrationFilter"]),
("/.*", ["httpSessionContextIntegrationFilter",
"exception_translation_filter",
"auth_processing_filter",
"filter_security_interceptor"])
])

@Object
def httpSessionContextIntegrationFilter(self):
filter = HttpSessionContextIntegrationFilter()
filter.sessionStrategy = self.session_strategy()
return filter

@Object
def session_strategy(self):
return CP3SessionStrategy()

@Object
def exception_translation_filter(self):
filter = ExceptionTranslationFilter()
filter.authenticationEntryPoint = self.auth_filter_entry_pt()
filter.accessDeniedHandler = self.accessDeniedHandler()
return filter

@Object
def auth_filter_entry_pt(self):
filter = AuthenticationProcessingFilterEntryPoint()
filter.loginFormUrl = "/login"
filter.redirectStrategy = self.redirectStrategy()
return filter

@Object
def accessDeniedHandler(self):
handler = SimpleAccessDeniedHandler()
handler.errorPage = "/accessDenied"
handler.redirectStrategy = self.redirectStrategy()
return handler

@Object
def redirectStrategy(self):
return CP3RedirectStrategy()

@Object
def auth_processing_filter(self):
filter = AuthenticationProcessingFilter()
filter.auth_manager = self.auth_manager()
filter.alwaysReauthenticate = False
return filter

@Object
def auth_manager(self):
auth_manager = AuthenticationManager()
auth_manager.auth_providers = [self.auth_provider()]
return auth_manager

@Object
def auth_provider(self):
provider = DaoAuthenticationProvider()
provider.user_details_service = self.user_details_service()
provider.password_encoder = PlaintextPasswordEncoder()
return provider

@Object
def user_details_service(self):
user_details_service = InMemoryUserDetailsService()
user_details_service.user_dict = {
"alice": ("alicespassword",["ROLE_CUSTOMER"], True),
"bob": ("bobspassword", ["ROLE_MGR"], True),
"carol": ("carolspassword", ["ROLE_SUPERVISOR"], True)
}
return user_details_service


@Object
def filter_security_interceptor(self):
filter = FilterSecurityInterceptor()
filter.auth_manager = self.auth_manager()
filter.access_decision_mgr = self.access_decision_mgr()
filter.sessionStrategy = self.session_strategy()
filter.obj_def_source = [
("/.*", ["ROLE_CUSTOMER", "ROLE_MGR", "ROLE_SUPERVISOR"])
]
return filter

@Object
def access_decision_mgr(self):
access_decision_mgr = AffirmativeBased()
access_decision_mgr.allow_if_all_abstain = False
access_decision_mgr.access_decision_voters = [RoleVoter()]
return access_decision_mgr

import cherrypy

from springpython.security import *
from springpython.security.providers import *
from springpython.security.context import *

class SpringBankView(object):

def __init__(self):
self.filter = None
self.auth_provider = None
self.http_context_filter = None

@cherrypy.expose
def index(self):
return """
Welcome to SpringBank!
<p>
<p>
<a href="logout">Logout</a href>
"""

@cherrypy.expose
def login(self, from_page="/", login="", password="", error_msg=""):
if login != "" and password != "":
try:
self.attempt_auth(login, password)
raise cherrypy.HTTPRedirect(from_page)
except AuthenticationException, e:
raise cherrypy.HTTPRedirect(
"?login=%s&error_msg=Username/password failure"
% login)

return """
%s<p>
<form method="POST" action="">
<table>
<tr>
<td>Login:</td>
<td><input type="text" name="login"
value="%s"/></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password"/></td>
</tr>
</table>
<input type="hidden" name="from_page" value="%s"/><br/>
<input type="submit"/>
</form>
""" % (error_msg, login, from_page)

def attempt_auth(self, username, password):
token = UsernamePasswordAuthenticationToken(username, password)
SecurityContextHolder.getContext().authentication = \
self.auth_provider.authenticate(token)
self.http_context_filter.saveContext()

@cherrypy.expose
def logout(self):
self.filter.logout()
self.http_context_filter.saveContext()
raise cherrypy.HTTPRedirect("/")

完整的源代码可在url中找到: https://www.packtpub.com/sites/defau.../0660_Code.zip

谢谢


Tags: fromimportselfauthreturnobjectdefmanager