我正在尝试创建一种使用python和cherrypy的Web服务器。
我希望将htmls放入单独的文件中,并将它们嵌入到我的python脚本中。我以前用的代码是
@cherrypy.expose
def welcome(self, loginAttempt = None):
""" Prompt the user with a login form. The form will be submitted to /signin
as a POST request, with arguments "username", "password" and "signin"
Dispaly a login error above the form if there has been one attempted login already.
"""
#Debugging Process Check
print "welcome method called with loggedIn = %s" % (loginAttempt)
if loginAttempt == '1':
""" If the user has attempted to login once, return the original login page
with a error message"""
page = get_file("loginPageE.html")
return page
else:
page = """
<form action='/signin' method='post'>
Username: <input type='text' name='username' /> <br />
Password: <input type='password' name='password' />
<input type='submit' name='signin' value='Sign In'/>
</form>
"""
return page
其中loginPageE.html是
<html>
<head>
<title>Failed Login Page</title>
</head>
<body>
<!-- header-wrap -->
<div id="header-wrap">
<header>
<hgroup>
<h1><a href="loginPageE.html">Acebook</a></h1>
<h3>Not Just Another Social Networking Site</h3>
</hgroup>
<ul>
<form action='/signin' method='post'>
Username: <input type='text' name='username' />
Password: <input type='password' name='password' />
<input type='submit' name='signin' value='Sign In'/>
</form>
</ul>
</header>
</div>
</body>
</html>
然而,我不断收到一条错误消息,上面写着
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/cherrypy/_cprequest.py", line 606, in respond
cherrypy.response.body = self.handler()
File "/usr/lib/pymodules/python2.7/cherrypy/_cpdispatch.py", line 25, in __call__
return self.callable(*self.args, **self.kwargs)
File "proj1base.py", line 74, in welcome
page = get_file("loginPageE.html")
NameError: global name 'get_file' is not defined
我想知道是否有人能帮忙?
提前感谢
从这个错误中,python显然不知道get_file()
函数是什么。你确定在welcome()
函数内部调用这个函数的时候,get_file()
已经定义好了吗?
get_file不是标准Python函数之一,所以它必须是您以前拥有的自定义函数。您可以创建一个简单的函数来读取文件并将其内容作为字符串返回,如下所示:
def get_file(path):
f = open(path, 'r')
output = f.read()
f.close()
return output
您可以在http://docs.python.org/tutorial/inputoutput.html#reading-和写入文件
def get_file(path):
with open(path, 'r') as f:
return f.read()
但是,请考虑使用适当的模板引擎。Jinja2真的很好,它允许你在模板中使用条件词等——这在某个时候你肯定会想要的。除此之外,如果你要求它,它还可以为你做一些很好的事情,比如变量自动转义。