Python 在呈现页面上获取404
我正在学习Tornado的模块和模板是如何工作的。在此特定示例中Python 在呈现页面上获取404,python,tornado,Python,Tornado,我正在学习Tornado的模块和模板是如何工作的。在此特定示例中http://localhost:8000/返回正确的页面,但http://localhost:8000/recommended返回404和以下说明: Traceback (most recent call last): File "/home/stefan/.local/lib/python3.6/site-packages/tornado/web.py", line 1676, in _execute result
http://localhost:8000/
返回正确的页面,但http://localhost:8000/recommended
返回404和以下说明:
Traceback (most recent call last):
File "/home/stefan/.local/lib/python3.6/site-packages/tornado/web.py", line 1676, in _execute
result = self.prepare()
File "/home/stefan/.local/lib/python3.6/site-packages/tornado/web.py", line 2431, in prepare
raise HTTPError(self._status_code)
tornado.web.HTTPError: HTTP 404: Not Found
这是我的main.py
import os.path
import tornado.web
import tornado.httpserver
import tornado.ioloop
import tornado.options
from tornado.options import define, options
define("port", default=8000, help="run on given port", type=int)
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", MainHandler),
(r"/recommended/", RecommendedHandler),
]
settings = dict(
template_path = os.path.join(os.path.dirname(__file__),"templates"),
static_path = os.path.join(os.path.dirname(__file__),"static"),
ui_modules = {"Book" : BookModule },
debug=True,
)
tornado.web.Application.__init__(self,handlers,**settings)
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render("index.html", page_title="Burt's Books | Home ", header_text = "Welcome to Burt's Books!",)
class RecommendedHandler(tornado.web.RequestHandler):
def get(self):
self.render(
"recommended.html",
page_title = "Burt's Books | recommended Reading",
header_text = "Recommended Reading",
books = [
{
"title" : "Programming Collective Intelligence",
},
...
]
)
class BookModule(tornado.web.UIModule):
def render(self,book):
return self.render_string("modules/book.html", book=book)
if __name__ == "__main__":
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
我的工作目录的结构是:
伯特的书/
/static
/templates
/modules
book.html
index.html
main.html
recommeneded.html
main.py
如果需要,我可以在评论中发布其他文件的内容。看起来您正在请求
/recommended
,但您的映射是/recommended/
。我总是在路径结构的末尾添加一个问号,以确保正则表达式同时包含这两个部分。尝试将代码更改为以下内容:
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", MainHandler),
(r"/recommended/?", RecommendedHandler),
]
...
谢谢你的帮助。但是,我得到了以下错误:
Traceback(最近一次调用最后一次):。。。在render_string return t.generate(**namespace)文件“/home/stefan/.local/lib/python3.6/site packages/tornado/template.py”的第361行,在generate return execute()文件“modules/book_html.generated.py”的第5行,在_tt_execute__tmp=book[“title”]#modules/book.html:2 TypeError:“省略号”对象不可订阅
我只能在这里发布完整的错误,所以我发布了我认为最重要的内容。我忘了添加,Python版本是3.6.8,Tornado版本是6.0.3。这是打字错误,我没有在book.html的{book[“subtitle”]}
中键入]
括号。再次感谢。