如何使用python和self.request.path将多个处理程序组合成一个

时间:2016-02-06 06:21:35

标签: python html web handlers google-app-engine-python

我目前正在使用python,html和google app引擎为我的网页设计课程创建一个非常基本的网站。我能够使用多个处理程序使网站,但我们应该只使用一个处理程序创建一个多页面网站。

我可以获得如下处理程序:

class IndexHandler(webapp2.RequestHandler):
  def get(self):
    template = JINJA_ENVIRONMENT.get_template('templates/index.html'))
    self.response.write(template.render({'title': 'HOME', 'header':'HOME'}))

class FriendHandler(webapp2.RequestHandler):
  def get(self):
    template = JINJA_ENVIRONMENT.get_template('templates/friends.html')
    self.response.write(template.render({'title': "FRIENDS", 'header': "FRIENDS"}))

工作,但当我尝试使用以下方法组合它们时:

class AllTheHandlers(webapp2.RequestHandler):
  def get(self):
    template = JINJA_ENVIRONMENT.get_template('templates%s' % self.request.path)
    self.response.write(template.render({'title', 'header'}))
    outstr = template.render(temp, { })
    self.response.out.write(outstr)

我收到404错误,我的日志显示:

INFO     2016-02-06 06:14:13,445 module.py:787] default: "GET / HTTP/1.1" 404 154

任何帮助都会非常感激,即使是关于如何使用self.request.path属性的指针也会对我有所帮助。我觉得我的问题的一部分与我的代码结束有关,但我不确定:

app = webapp2.WSGIApplication([
    ('/', AllTheHandlers),
    # ('/bio.html', AllTheHandlers),
    # ('/index.html', AllTheHandlers),
    # ('/friends.html', AllTheHandlers),
    # ('/horses.html', AllTheHandlers),
], debug=True)

感谢您提供的任何帮助!

1 个答案:

答案 0 :(得分:1)

Error 404表示您的RequestHandler甚至无法联系到。问题出在URI routing

目前,您只配置了一条路线:

app = webapp2.WSGIApplication([
    ('/', AllTheHandlers),

这并不意味着/及其下的一切,正如您所期望的那样。这意味着/,而不是其他任何内容。

如果您想提供多个简单的html模板,可以按照以下步骤进行更改:

class AllTheHandlers(webapp2.RequestHandler):
  def get(self, html_page):
    template = JINJA_ENVIRONMENT.get_template('templates/%s' % html_page)
    # ...

app = webapp2.WSGIApplication([
    ('/(\w+\.html)', AllTheHandlers),
], debug=True)

(\w+\.html)是与someword.html匹配的regular expression。因为我们把它放在括号中,所以它被捕获并转移到get()作为参数。然后我们可以简单地选择合适的模板。

免责声明:上述代码不应被视为一种良好做法 - 它只是说明路由的工作原理。