为什么会出现 KeyError?

Why do I get a KeyError?

这是我的代码:

import web
import json

urls = (
    '/', 'index'
    '/runs', 'runs'
)
app = web.application(urls, globals())
class index:
    def GET(self):
        render = web.template.render('templates/')
        return render.index()

class runs:
    def GET(self):
        return "Test"

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

我收到以下错误:

Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/web/application.py", line 239, in process
return self.handle()
File "/usr/local/lib/python2.7/dist-packages/web/application.py", line 230, in handle
return self._delegate(fn, self.fvars, args)
File "/usr/local/lib/python2.7/dist-packages/web/application.py", line 419, in _delegate
cls = fvars[f]
KeyError: u'index/runs'

大多数人似乎忘记实际创建 class(在我的例子中是运行)或者在需要时无法导入它。除了检查这些东西,我没有找到任何其他解决方案。

您忘记了一个逗号:

urls = (
    '/', 'index'
#               ^
    '/runs', 'runs'
)

没有逗号,Python连接了两个连续的字符串,所以你真的注册了:

urls = (
    '/', 'index/runs', 'runs'
)

而你的 globals() 词典中没有这样的功能。

如果我在逗号中添加您的代码有效。

您的代码有错别字:

urls = (
    '/', 'index', # missing comma
    '/runs', 'runs'
)