AttributeError:'Response'对象在packages\django\middleware\common.py中没有属性'streaming'

eblbsuwk  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(118)

使用requests,我们无法获得200成功代码,这是由于公共文件中的错误或发送请求或接收响应的错误方式。以下是技术细节:

调用脚本

import requests
try:
 post_data = {'langs': langs, 'langs_json': []}
 # filling post_data..
 response = requests.post(api_call_url, json=post_data, verify=False)
return JsonResponse({}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
except Exception as e:
return JsonResponse({}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

字符串

服务脚本

@csrf_exempt
def api_end_point(request):
    try:
        data = json.loads(request.body.decode('utf-8-sig'))
        with open(os.path.join(r'assets\i18n', f'fr.json'), 'w', encoding='utf-8-sig') as f:
            json.dump(data['langs_json'][0], f)
        with open(os.path.join(r'assets\i18n', f'en.json'), 'w', encoding='utf-8-sig') as f:
            json.dump(data['langs_json'][1], f)
        # All works above.. the issue has something to do with the response itself..
        response = JsonResponse(dict(status=True), safe=False, status=status.HTTP_200_OK)
        response.status_code = 200 # trying to solve..
        return response
    except Exception as e:
        response = JsonResponse(dict(status=False), safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        response.status_code = 500 # trying to solve..
        return response

错误消息

File "C:\Users\***\Desktop\****\*****\*****\venv\lib\site-packages\django\middleware\common.py", line 112, in process_response
if not response.streaming and not response.has_header('Content-Length'):
AttributeError: 'Response' object has no attribute 'streaming'

common.py snippet

def process_response(self, request, response):
    """
    When the status code of the response is 404, it may redirect to a path
    with an appended slash if should_redirect_with_slash() returns True.
    """
    # If the given URL is "Not Found", then check if we should redirect to
    # a path with a slash appended.
    if response.status_code == 404 and self.should_redirect_with_slash(request):
        return self.response_redirect_class(self.get_full_path_with_slash(request))

    # Add the Content-Length header to non-streaming responses if not
    # already set.
    if not response.streaming and not response.has_header('Content-Length'):
        response.headers['Content-Length'] = str(len(response.content))

    return response

t5fffqht

t5fffqht1#

在你的脚本中,你返回了一个Response对象,它是从try块中的requests.post(•••)调用中获得的。请注意,这个Response对象是由requests Python library定义的。
然后在catch块中,返回Django定义的JsonResponse
你现在看到错误了吗?来自requests.post(•••)ResponseJsonResponse的类型不同。它们来自两个不同的库/框架。

相关问题