Python - 异常 "没有名为 index 的模板" 在 lpthw.web 框架中
我正在学习一个简短的Python教程,但最后一个练习我搞不定。
这是app.py的源代码:
import web
urls = (
'/', 'Index'
)
app = web.application(urls, globals())
render = web.template.render('templates/')
class Index(object):
def GET(self):
greeting = "Hello World"
return render.index(greeting = greeting)
if __name__ == "__main__":
app.run()
这是视图文件index.html:
$def with (greeting)
<html>
<head>
<title>Gothons of Planet Percal #25</title>
</head>
<body>
$if greeting:
I just wanted to say <em style="color: green; font-size: 2em;">
greeting</em>.
$else:
<em>Hello</em>, world!
</body>
</html>
文件app.py在这个目录下:C:\Users\Lucas\Desktop\Learn Python The Hard Way\ex50\gothonweb\bin,
而index.html在:C:\Users\Lucas\Desktop\Learn Python The Hard Way\ex50\gothonweb\templates。
所以,当我想运行示例代码时,我在命令提示符下输入这个:
C:\Python26\python.exe "C:\Users\Lucas\Desktop\Learn Python The Hard Way\ex50\gothonweb\bin\app.py"
之后,控制台上显示"http://0.0.0:8080",于是我在浏览器中打开http://localhost:8080/,
但我却看到一大堆错误信息,开头是:
<type 'exceptions.AttributeError'> at /
No template named index
Python C:\Python26\lib\site-packages\web\template.py in _load_template, line 992
Web GET http://localhost:8080/
这是怎么回事,我该怎么解决呢?
提前谢谢你们!
6 个回答
你有几个拼写错误,当你使用 render
的时候,需要把你的视图称作 Index
(这需要和你路由的类名一致):
return render.Index(greeting = greeting)
而且你的 urls
元组后面需要加一个逗号:
urls = (
'/', 'Index',
)
另外,确保你的模板文件叫做 Index.html
。不过,从 web.py 教程 看,通常情况下,你的路由类名应该用小写字母。
在Windows系统中,文件夹的名称必须这样写:“c:\”,而不是“c/”。而且你需要使用完整的路径。所以正确的代码是 render = web.template.render('d:\\documents\\python\\templates\\')
(app.py文件在d:\documents\python目录下)。
我也遇到过这个问题,不过是在OSX系统上。最后,Zed Shaw看到我求助的信息,发现了我犯的错误。
我当时运行的是:
~/projects/gothonweb/bin $ python app.py
Zed提醒我,我需要运行这个:
~/projects/gothonweb $ python bin/app.py
这样才能找到模板文件夹。做完这个之后,一切都顺利了。