Django无法多次访问请求

时间:2017-04-08 18:25:57

标签: python json ajax django

我有使用ajax编辑用户配置文件的视图,我正在检查请求类型,如果它的帖子只是通过request.body获取Json数据。但是Django给了我一个错误:'从请求的数据流中读取后你无法访问正文'。显然我只能访问一个请求数据,所以如何在阅读正文之前检查请求类型。这是简化代码

def edit_profile(request):
    if request.method == 'POST':
        name = ''
        email = ''
        bio = ''
        user_profile = User.objects.get(username=request.user.username)

        try:
            req_str = request.body.decode('utf-8')
            req_json = json.loads(req_str)

            name = req_json['username']
            email = req_json['email']
            bio = req_json['bio']

            if name:
                user_profile.username = name
            if email:
                user_profile.email = email
            if bio:
                user_profile.account.bio = bio

            user_profile.save()
            user_profile.account.save()
        except KeyError:
            print("can't parse json")
        except Exception as e:
            print('fialed to proccess request', e)

        return JsonResponse({
            'username': user_profile.username,
            'email': user_profile.email,
            'bio': user_profile.account.bio
        })
    else:
        return HttpResponse('nothing changed')

完整的错误消息:

Internal Server Error: /accounts/edit_profile/
Traceback (most recent call last):
  File "/home/void/Projects/workspace/venv/lib/python3.4/site-packages/django/core/handlers/exception.py", line 42, in inner
    response = get_response(request)
  File "/home/void/Projects/workspace/venv/lib/python3.4/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/void/Projects/workspace/venv/lib/python3.4/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/void/Projects/workspace/workspace/accounts/views.py", line 79, in edit_profile
    req_str = request.body.decode('utf-8')
  File "/home/void/Projects/workspace/venv/lib/python3.4/site-packages/django/http/request.py", line 264, in body
    raise RawPostDataException("You cannot access body after reading from request's data stream")
django.http.request.RawPostDataException: You cannot access body after reading from request's data stream

1 个答案:

答案 0 :(得分:0)

您的中间件必须访问可能导致错误的request.body,请检查您的MIDDLEWARE_CLASSES以查找可能正在访问数据的任何自定义/中间件。检查您在中间件中使用的模块/应用程序是否存在此错误。

这里有一些很好的解释。 https://stackoverflow.com/a/28641930/3448851