在process_response上调用request.session.save时,自定义会话中间件上的Django错误

时间:2019-01-23 14:54:47

标签: python django middleware

Traceback (most recent call last):
  File "/home/user/.virtualenvs/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/user/.virtualenvs/env/lib/python3.6/site-packages/django/utils/deprecation.py", line 93, in __call__
    response = self.process_response(request, response)
  File "/home/user/Desktop/project/my_project/app1/middleware.py", line 98, in process_response
    request.session.save()
  File "/home/user/.virtualenvs/env/lib/python3.6/site-packages/django/contrib/sessions/backends/db.py", line 83, in save
    obj = self.create_model_instance(data)
  File "/home/user/.virtualenvs/env/lib/python3.6/site-packages/django/contrib/sessions/backends/db.py", line 70, in create_model_instance
    session_data=self.encode(data),
  File "/home/user/.virtualenvs/env/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py", line 96, in encode
    serialized = self.serializer().dumps(session_dict)
  File "/home/user/.virtualenvs/env/lib/python3.6/site-packages/django/core/signing.py", line 87, in dumps
    return json.dumps(obj, separators=(',', ':')).encode('latin-1')
  File "/usr/local/lib/python3.6/json/__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "/usr/local/lib/python3.6/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/local/lib/python3.6/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/usr/local/lib/python3.6/json/encoder.py", line 180, in default
    o.__class__.__name__)
TypeError: Object of type '__proxy__' is not JSON serializable

我已经通过记录每个值及其类型来检查request.session.keys中的值。没有一个__proxy__对象。 另外,str不太可能实际上是Django函数。__proxy__对象或某些翻译对象,因为它会显示出来。可能是Django错误吗?

Django == 2.1.4 我正在使用的中间件

class CustomMiddleware(SessionMiddleware):
   ...

这仅发生在我的一个处理post方法并返回JSON响应的视图中,因此导致此错误的变量不太可能像调用render_json_response(context)

时那样来自视图

1 个答案:

答案 0 :(得分:0)

感谢您的评论,帮助我意识到我错过了一些东西。 我使用此代码段捕获了错误的变量。

for key in session.keys():
    try:
        json.dumps(session[key])
    catch Exception as e:
        print(key)