Python - lpthw.web框架中的异常“没有名为index的模板”

时间:2011-08-24 17:32:08

标签: python

我正在阅读一篇简短的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 个答案:

答案 0 :(得分:3)

我也有这个问题,但在OSX上运行。最终Zed Shaw看到了我的求助请求,看到了我正在犯的错误。

我在跑

~/projects/gothonweb/bin $ python app.py

Zed提醒我,我需要运行这个:

~/projects/gothonweb $ python bin/app.py

允许找到templates文件夹。在我这样做之后,它就像一个魅力。

答案 1 :(得分:2)

在Windows中,文件夹'name必须写成这样的“c:\”而不是“c /”,你必须使用完整路径。 所以正确的代码是render = web.template.render('d:\\documents\\python\\templates\\') (app.py在d:\ documents \ python中)

答案 2 :(得分:1)

您有一些拼写错误,当您使用Index(需要与路线的班级名称相同)时,您需要将您的观点称为render

return render.Index(greeting = greeting)

您的urls元组需要一个尾随逗号:

urls = (
    '/', 'Index',
)

还要确保您的模板名为Index.html。虽然看一下web.py tutorial,但按照惯例看,你的路线类会使用小写字母。

答案 3 :(得分:1)

好吧,我遇到了同样的问题,我必须说错误信息是正确的,这表明“你”找不到文件,只是因为你没有找到正确的道路。所以@davidheller @shellfly是对的。

我使用PyCharm作为IDE来编写python,所以这是我的解决方案: 因为我运行了bin目录下的app.py,因此render = web.template.render('../templates/') 其中..上升然后找到了该文件。

总之,我们必须确定当前路径(即使在Windows中),并且相对路径或绝对路径都可以在Windows环境中使用,如下所示:

  1. 绝对路径。

    绝对路径。由于Windows同时接受“/”和“\”,我们可以编写

    render = web.template.render('C:/Users/Lucas/Desktop/Learn Python The Hard Way/ex50/gothonweb/templates/')
    

    render = web.template.render('C:\\Users\\Lucas\\Desktop\\Learn Python The Hard Way\\ex50\\gothonweb\\templates\\')
    

    注意,python解释器将"\\"解释为"\"

  2. 相对路径。

    render = web.template.render('../templates/')
    

答案 4 :(得分:0)

您可能需要像这样编译模板

python web / template.py - 编译模板

任何将web.py与您需要的Google应用引擎一起使用的人。

答案 5 :(得分:0)

我正在做同样的练习,我只是继续使用cmd,cd到我的lpthw目录,里面包含项目骨架的文件夹并执行:

> python bin/app.py 

我认为您必须将项目框架中的所有文件放在一个文件夹中,然后从那里运行您的应用程序。希望这可以帮助。 :)

相关问题