繁体   English   中英

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

[英]Python - Exception “No template named index” in lpthw.web framework

我正在阅读一篇简短的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 Hard Way \\ ex50 \\ gothonweb \\ bin和index.html位于:C:\\ Users \\ Lucas \\ Desktop \\ Learn Python The Hard路\\ EX50 \\ gothonweb \\模板

因此,当我想运行示例代码时,我在命令提示符下键入:

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/

发生了什么,我该如何解决?

提前致谢!

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

我之前在跑步

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

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

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

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

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

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

我使用PyCharm作为IDE来编写python,所以这是我的解决方案:因为我运行app.py,它位于bin目录下,因此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/') 

你有一些拼写错误,你需要在使用render时将你的视图称为Index (需要与你的路线的类名相同):

return render.Index(greeting = greeting)

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

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

还要确保您的模板名为Index.html 虽然,看一下web.py教程 ,看起来按照惯例,你会为你的路由类使用小写。

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

python web / template.py - 编译模板

任何使用web.py和Google应用引擎的人都需要。

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

> python bin/app.py 

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM