Why do I get a KeyError?

邮差的信 提交于 2019-12-13 20:53:20

问题


This is my code:

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()

And I get the following error:

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'

Mostly people seem to forget to actually create the class (in my case runs) or fail at importing it if needed. I didn't find any other solution than checking these things.


回答1:


You forgot a comma:

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

Without the comma, Python concatenates the two consecutive strings, so you really registered:

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

and you have no such function in your globals() dictionary.

If I add in the comma your code works.




回答2:


Your code has a typo:

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


来源:https://stackoverflow.com/questions/30461384/why-do-i-get-a-keyerror

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!