0

好的,所以这看起来应该很基本,但我就是无法让它工作。我收到一个 404 错误,提示找不到资源,但我被定向到正确的地址,例如 www.url.com/sea?s='1' 用于航行。我有一个具有不同查询参数的链接列表,我希望我的 python 代码对它们进行不同的处理。我正在使用带有 python 和 jinja2 模板系统的谷歌应用程序引擎。

这是我的 HTML:

  <h3><a href="/" class="center-it">Quick Navigation</a></h3>
    <div class="span1">
    <div class="span1">
      <h4><a href="/sea">Sea</a></h4>
        <ul>
            <li><a href="/sea?s='1'">Sailing</a></li>
            <li><a href="/sea?s='2'">Diving</a></li>
            <li><a href="/sea?s='3'">Surfing</a></li>
            <li><a href="/sea?s='4'">Kite Boarding</a></li>
            <li><a href="/sea?s='5'">Kayaking</a></li>
        </ul>
   </div>

这是蟒蛇:

class Sea(BlogHandler):
    def get(self, s):
        s = self.request.get('s')
        if s == '1':
            posts = posts = db.GqlQuery("select * from Post where sport=:1 order by created desc limit 30", "sailing")
        elif s == '2':
            posts = posts = db.GqlQuery("select * from Post where sport=:1 order by created desc limit 30", "diving")
        elif s == '3':
            posts = posts = db.GqlQuery("select * from Post where sport=:1 order by created desc limit 30", "surfing")
        elif s == '4':
            posts = posts = db.GqlQuery("select * from Post where sport=:1 order by created desc limit 30", "kiteboarding")
        elif s == '5':
            posts = posts = db.GqlQuery("select * from Post where sport=:1 order by created desc limit 30", "kayaking")
        else:
            posts = posts = db.GqlQuery("select * from Post where element=:1 order by created desc limit 30", "sea")

        global visits
        user = users.get_current_user()
        logout = users.create_logout_url(self.request.uri)        
        self.render('sport.html', user = user, posts=posts, visits = visits, logout=logout)

更新:问题实际上不在于我的 URL 处理的代码。这是对的:

app = webapp2.WSGIApplication([('/', MainPage),
                               (r'/sea', Sea)]
4

1 回答 1

1

出现 404 错误不是因为您的页面有任何问题,而是因为您的路线或 app.yaml 文件有问题。如果您使用的是 webapp2,您只需要定义一个包含 url 的路由,r'/air'它应该可以工作。(例如webapp2.Route(r'/sea/', handler=Sea)

顺便说一句,您可以将它们作为 route kwargs 并做更好的事情,而不是在您的 get 请求中使用查询字符串,例如(语法是<KEYWORDNAME:REGULAREXPRESSION>当没有给出关键字名称时(如 in <:/?>)它只匹配正则表达式并且不不要把任何东西传给你)

webapp2.Route(r'/sea<:/?><activity:[a-zA-Z]*?>', defaults={"activity":""}, handler=Sea, name="sea")

然后您可以将您的网址更改为,例如:

<a href="/sea/sailing">Sailing</a>

您需要进行的唯一其他更改是在您的 Handler 函数中。它需要接受 kwargs。(所以你可以从字面上稍微改变你的获取请求):

get(self, *args, **kwargs):
    activity = kwargs.get("activity")
    if activity in ("sailing", "kayaking", "hiking", "kiteboarding", "surfing", "diving")
       posts = db.GqlQuery("select * from Post where sport=:1 order by created desc limit 30", activity)
    elif activity:
       self.error(404)
    else:
       posts = db.GqlQuery ... etc

这将大大简化您的代码,并让您使其更加灵活。此外,如果您的网站不经常更新,您可以做一些缓存以使查询更快捷,等等。

于 2012-06-30T06:22:13.337 回答