1

我正在编写一个带有 SEO 友好 URL 的博客应用程序。当我访问无效的网址时,我收到以下错误:

UnboundLocalError:分配前引用的局部变量“路径”

有效的网址工作正常。

这是代码:

class ViewPost(BaseHandler):
    def get(self, slug):
        post = Posts.all()
        post.filter('path =', slug)
        results = post.fetch(1)
        for post in results:
            path = post.path
        if path == slug:
            self.render_template('post.html', {'post':post})
        else:
            self.response.out.write('no post with this slug')

以下是没有错误的有效示例和引发错误的无效示例。您可以在无效示例中看到完整的堆栈跟踪。

完整代码在github第 62 行。

提前致谢。我是 python 新手,所以非常感谢您的帮助和反馈。

更新

  1. 对于上下文,我正在比较两个字符串以确定我是否有要提供的内容。

  2. 我期望看到的:如果 slug 和 path 相等,它应该呈现模板。如果不相等:它应该以“no post with this slug”消息进行响应。

  3. 我做过的其他事情。

    • 我已经验证我得到了一个 slug 和路径值。

    • 我试过改变这样的想法。

这阻止了我得到错误,但我没有得到我的 else 响应。相反,我得到一个空白页面,在源代码中没有任何内容。

class ViewPost(BaseHandler):
def get(self, slug):
    post = Posts.all()
    post.filter('path =', slug)
    results = post.fetch(1)
    for post in results:
        path = post.path
        if path == slug:
            self.render_template('post.html', {'post':post})
        else:
            self.response.out.write('no post with this slug')
4

1 回答 1

1

在此版本的代码中,您会看到空白页,因为从未输入过 for 循环。由于 slug 无效,结果为 null 或空。结果,永远不会到达 if 语句,这意味着 if 和 else 都不会触发。

class ViewPost(BaseHandler):
def get(self, slug):
    post = Posts.all()
    post.filter('path =', slug)
    results = post.fetch(1)
    for post in results:
        path = post.path
        if path == slug:
            self.render_template('post.html', {'post':post})
        else:
            self.response.out.write('no post with this slug')

在此示例中,您的缩进设置为始终到达 if 语句,而与 slug 无关。但是,如上例所示,结果要么为空,要么为空。for 循环永远不会运行,这意味着您的路径变量永远不会设置。

class ViewPost(BaseHandler):
    def get(self, slug):
        post = Posts.all()
        post.filter('path =', slug)
        results = post.fetch(1)
        for post in results:
            path = post.path
        if path == slug:
            self.render_template('post.html', {'post':post})
        else:
            self.response.out.write('no post with this slug')

当尝试比较时,这当然会导致以下错误消息path == slug

UnboundLocalError:分配前引用的局部变量“路径”

基本上,要解决这个问题,您需要使用一个值初始化路径,以便在没有赋值的情况下不会引用它。将 path 设置为保证与您的 slug 不同的默认值,如果 slug 没有导致有效的记录,那么您的 else 将触发。

解决方案:

带有 `path = 'none` 的示例,以及缩进设置,以便始终到达 if 语句。

class ViewPost(BaseHandler):
    def get(self, slug):
        path = 'none'
        post = Posts.all()
        post.filter('path =', slug)
        results = post.fetch(1)
        for post in results:
            path = post.path
        if path == slug:
            self.render_template('post.html', {'post':post})
        else:
            self.response.out.write('no post with this slug')
于 2012-05-18T07:35:30.387 回答