简体   繁体   English

尝试在Django中遍历会话字典时的KeyError 0

[英]KeyError 0 when trying to traverse session dictionary in Django

I'm trying to traverse the session variable to print out all of its contents. 我正在尝试遍历会话变量以打印出其所有内容。

for s in request.session:
    print str(s)

The resulting error is as follows 产生的错误如下

KeyError at /<app name>/searchResults/
0

With the following traceback. 通过以下回溯。

/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in get_response
    115. response = callback(request, *callback_args, **callback_kwargs)

/<path to django app>/views.py
    106. for s in request.session:

/usr/local/lib/python2.7/dist-packages/django/contrib/sessions/backends/base.py in __getitem__
    46 return self.__session[key]

Any idea what '0' means as an error? 知道什么是'0'意味着什么错误? I've never seen this kind of thing before. 我以前从未见过这种事。

The correct way to iterate over the session's values is request.session.itervalues() - the base session class exposes the same key/value/item options as a standard dictionary. 迭代会话值的正确方法是request.session.itervalues() - 基本会话类公开与标准字典相同的键/值/项选项。 I am unsure so far where it's getting the values your for loop is finding, but it's not the values. 到目前为止,我不确定它正在获取你的for循环所找到的值,但它不是值。

You class is missing the __iter__ member... thats all. 你的班级缺少__iter__成员......就是这样。

You can probably subclass it to fix the bug. 您可以将其子类化以修复错误。

eg 例如

class IterableRequest(Request):
  def __iter__(self): return self.iterkeys()

Maybe this next hack might fix the problem: 也许这个下一个黑客可能会解决这个问题:

Request.__iter__=Request.iterkeys

See also: 也可以看看:

I'd be tempted to check the source and confirm it is a bug, and then make a bug report. 我很想检查源并确认它是一个bug,然后制作一个bug报告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM