我正在为项目使用cherrypy,并在主要的python脚本main.py中使用它
在主应用程序的一种方法中,我导入一个称为身份验证的模块from authentication import auth
,然后将变量args传递给它。显然已经在这里使用cherrypy
@cherrypy.expose
def auth(self, *args):
from authentication import auth
auth = auth()
page = common.header('Log in')
authString = auth.login(*args)
if authString:
page += common.barMsg('Logged in succesfully', 1)
page += authString
else:
page += common.barMsg('Authentication failed', 0)
page += common.footer()
return page
在authentication.py中,我想设置会话变量,因此我再次包含了cherrypy
def login(self, *args):
output = "<b>"args" has %d variables</b><br/>\n" % len(args)
if cherrypy.request.body_params is None:
output += """<form action="/auth/login" method="post" name="login">
<input type="text" maxlength="255" name="username"/>
<input type="password" maxlength="255" name="password"/>
<input type="submit" value="Log In"></input>
</form>"""
output += common.barMsg('Not a member yet? Join me <a href="/auth/join">here</a>', 8)
return output
问题是使用此错误时出现
HTTPError: (400, 'Unexpected body parameters: username, password')
错误。我想让main.py中的cherrypy实例在authentication.py中可以在此处设置会话变量。我怎样才能做到这一点?我也尝试过像
authString = auth.login(cherrypy, *args)
这样传递cherrypy对象,并省略了它包含在authentication.py中,但是得到了同样的错误 最佳答案
很抱歉回答这么快,但是经过一些研究后发现,方法auth中省略了** kwargs参数,导致body_parameters被cherrypy拒绝了,因为这不是期望的。要解决此问题:
main.py
@cherrypy.expose
def auth(self, *args, **kwargs):
from authentication import auth
auth = auth()
page = common.header('Log in')
authString = auth.login(cherrypy, args)
if authString:
page += common.barMsg('Logged in succesfully', 1)
page += authString
else:
page += common.barMsg('Authentication failed', 0)
page += common.footer()
return page
authentication.py
def login(self, cherrypy, args):
output = "<b>"args" has %d variables</b><br/>\n" % len(args)
if cherrypy.request.body_params is None:
output += """<form action="/auth/login" method="post" name="login">
<input type="text" maxlength="255" name="username"/>
<input type="password" maxlength="255" name="password"/>
<input type="submit" value="Log In"></input>
</form>"""
output += common.barMsg('Not a member yet? Join me <a href="/auth/join">here</a>', 8)
return output
关于python - 在两个模块中使用cherrypy,但只有一个cherrypy实例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9984839/