gpt4 book ai didi

python - cherrypy SessionAuth 不起作用?

转载 作者:行者123 更新时间:2023-12-01 05:49:21 24 4
gpt4 key购买 nike

我可能忽略了一些简单的事情,但我无法让 Cherrypy SessionAuth 工作。

在调试打开且cherrypy.session中没有用户名的情况下,SessionAuth会将其放入日志文件中:

[20/Feb/2013:00:58:39] TOOLS.SESSAUTH No username, routing to login_screen with from_page 'http://localhost:8080/'

问题是它无法路由到登录屏幕。它向调用者返回true,调用者继续执行。它还将cherrypy.serving.response.body 设置为呈现到登录页面的html 片段。但我的调用函数对response.body一无所知。

我做错了什么?

以下是 root.py 中的相关代码:

class MySessionAuth(cptools.SessionAuth):

def check_username_and_password(self, username, password):
users = dict(foo="bar")
if username in users and password == users[username]:
return False

def on_check(self, username):
cherrypy.session['username'] = username


def session_auth(**kwargs):
sa = MySessionAuth()
for k, v in kwargs.items():
setattr(sa, k, v)
return sa.run()

cherrypy.tools.protect = cherrypy._cptools.Tool('before_handler', session_auth)


class Root:
@cherrypy.expose()
@cherrypy.tools.protect(debug=True)
def index(self):
tmpl = loader.load('index.html')
return tmpl.generate(flash = '',).render('html', doctype='html')

最佳答案

如果您想通过密码保护整个应用程序而不仅仅是某些资源,您可以为 check_username_and_password 创建自定义函数,并在应用程序配置中让 check_username_and_password 指向它。要添加的配置行会像这样

'tools.session_auth.check_username_and_password':check_username_and_password

然后只需使用上面的自定义 check_username_and_password 就可以了。

这是一个完整的示例,它将保护应用程序中的所有资源

import cherrypy
from datetime import datetime

user_dict={'peter':'password','joe':'pass1234','tom':'!Sm,23&$fiuD'}
def check_user(username,password):
if user_dict.has_key(username):
if user_dict[username] == password:
return
else:
return 'incorrect password for user'
return 'user does not exist'

class Root:
@cherrypy.expose
def index(self):
cherrypy.session.regenerate()
cherrypy.session['access_datetime'] = datetime.now()
return """Hello protected resource! <br \>
datetime of access was %s
<br /><a href="./logout">Logout</a>"""%cherrypy.session['access_datetime']


@cherrypy.expose
def logout(self):
username = cherrypy.session['username']
cherrypy.session.clear()
return """%s you have been logged out
of the system at datetime %s"""%(username,datetime.now())

_cp_config={'/':{'tools.sessions.on':True,
'tools.sessions.storage_type':'file',
'tools.sessions.storage_path':'./',
'tools.sessions.timeout':60,
'tools.session_auth.on':True,
'tools.session_auth.check_username_and_password':check_user,
}
}
cherrypy.config.update({'server.socket_host':'0.0.0.0',
'server.socket_port':8090})
cherrypy.quickstart(Root(),'/',config=_cp_config)

关于python - cherrypy SessionAuth 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14973669/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com