学习途中练习50

2024-04-26 21:56:50 发布

您现在位置:Python中文网/ 问答频道 /正文

这显然是一个简单的问题,但我似乎不明白。在LPTHW Exercise 50中,我被要求创建一个网页foo.html. 我已经完成了这项工作,并将其保存在项目框架的templates文件夹中。在

当我在浏览器中输入http://localhost:8080时,它会自动找到索引.html该怎么翻就怎么翻。文件路径是Python/projects/gothonweb/templates/index.html

但是当我试图找到foo.html通过在下面输入任何一页我都找不到它。它的文件路径是Python/projects/gothonweb/templates/foo.html

http://localhost:8080/foo.html
http://localhost:8080/templates/foo.html
http://localhost:8080/gothonweb/templates/foo.html
http://localhost:8080/projects/gothonweb/templates/foo.html
http://localhost:8080/Python/projects/gothonweb/templates/foo.html

这是我第一次在网上使用python,任何帮助都将不胜感激


Tags: 文件项目路径文件夹框架localhosthttp网页
2条回答

你在这里建立一个web服务,而不是一个静态的网站。您的.html文件是用于构建动态页面的模板,而不是用于提供服务的静态页面。所以,如果web.py允许您自动访问foo.html,那就不好了。在

如果您查看日志输出,它实际上并不是为/index.html处理GET,而是使用templates/index.html来处理GET到{}。在

无论如何,它所提供的服务完全由您在app.py中编写的代码驱动,您已经告诉它在这里提供什么:

urls = (
  '/', 'index'
)

这说明了对/的请求应该由index类的实例来处理。那堂课是这样的:

^{pr2}$

换句话说,它不会“自动定位索引.htmlpage as it should”,它自动定位index类,该类使用显式指向index.html(通过render.index位)的呈现器。在

本练习明确解释了所有这些,然后要求您:

Also create another template named templates/foo.html and render that using render.foo() instead of render.index() like before.

所以,这就是你必须要做的。您必须使用render.foo()来呈现它。在

最简单的方法是:

urls = (
  '/', 'index',
  '/foo', 'foo'
)

# ...

class foo:
    def GET(self):
        greeting = "Foo"
        return render.foo(greeting=greeting)

有更灵活的方法来做事情,但你会在经历一个网页.py辅导的。(这项练习也要求你在继续之前做。)

您需要创建到foo.html文件的路由。在LPTHW练习50中,以下是您的bin/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()

注意以下几点:

  1. 您的routes变量urls只有一个到/路径的路由。在
  2. 在您调用的Index类中render.index

因此,你可以做的一件事,正如它在练习的学习练习之前建议的那样,就是简单地将render.index调用改为render.foo。在使用web框架的情况下,当加载索引路径时,这将呈现foo.html文件。在

您可以做的另一件事是向您的urls添加另一条路由,并创建一条class Foo来捕获该路由:

^{pr2}$

现在,当您转到http://localhost:8080/foo时,它将呈现您的foo.html模板。在

相关问题 更多 >