python - 学习Python困难之路练习 50

标签 python python-2.7

这显然是一个简单的问题,但我似乎无法理解。在 LPTHW Exercise 50我被要求创建一个网页 foo.html。我已经完成了此操作并将其保存在我的项目框架的模板文件夹中。

当我输入http://localhost:8080时进入浏览器后,它会自动定位到index.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,非常感谢任何帮助

最佳答案

您需要创建到 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. urls 变量(即您的路由)仅具有指向 / 路径的路由。
  2. Index 类中,您调用 render.index

因此,您可以做的一件事就是将 render.index 调用更改为 渲染.foo。使用 Web 框架时,这将在您加载索引路径时呈现 foo.html 文件。

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

import web

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

app = web.application(urls, globals())

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

class Index(object):
    def GET(self):
        greeting = "Hello World"
        return render.index(greeting = greeting)

class Foo(object):
    def GET(self):
        return render.foo()

if __name__ == "__main__":
    app.run()

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

关于python - 学习Python困难之路练习 50,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16740618/

相关文章:

python - 类型错误 : "quotechar" must be an 1-character string

python - 将python编译为exe

python - SQLAlchemy.exc.UnboundExecutionError : Could not locate a bind configured on mapper Mapper|SellsTable|sellers or this Session 错误

Python - 创建由变量组成的列表的最佳方法

python - 在 Windows 中测试时,使用 fasttext api 的监督分类返回空数组

python - String对象没有读取属性

python - subprocess.call() 与 GUI (Tkinter) 交互

python - Scrapy 内存错误(请求太多)Python 2.7

python - os的makedirs和mkdir有什么区别?

python - 如何提高这个脚本的性能?