You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用requests调用Django接口出现Response无streaming属性的AttributeError问题

使用requests调用接口无法获取200状态码问题排查

用requests库调用接口时无法获取200成功状态码,推测原因可能是common.py文件存在bug、请求发送方式错误或响应接收处理不当。以下是技术细节及修复方案:

调用脚本(原代码)

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)

调用脚本核心问题

代码缩进错误:return语句不在try块内,无论requests请求是否成功,都会直接返回500状态码,导致永远无法获取200响应。

服务端脚本(原代码)

@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代码片段

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

问题分析与修复方案

1. 修复调用脚本的缩进逻辑

调整return语句的缩进,使其在try块内根据请求结果返回对应状态码:

import requests
from django.http import JsonResponse
from django.http import HttpResponseStatus as status

def call_api_view(request):
    try:
        post_data = {'langs': langs, 'langs_json': []}
        # 填充post_data逻辑
        response = requests.post(api_call_url, json=post_data, verify=False)
        # 根据接口响应返回结果
        if response.ok:
            return JsonResponse({'status': True}, safe=False, status=status.HTTP_200_OK)
        else:
            return JsonResponse({'status': False}, safe=False, status=response.status_code)
    except Exception as e:
        return JsonResponse({'error': str(e)}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

2. 解决服务端的AttributeError问题

错误提示说明Django中间件处理的response对象不是Django的HttpResponse子类(缺少streaming属性),大概率是代码中导入了非Django的Response类(比如requests的Response),或错误返回了非Django响应对象。

  • 检查服务端代码的导入语句,确保没有错误导入:
    # 确保导入的是Django的JsonResponse
    from django.http import JsonResponse
    
  • 确认视图函数返回的始终是Django的HttpResponse及其子类(如JsonResponse),不要返回其他库的Response对象。

内容的提问来源于stack exchange,提问作者SDIdo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 10:07:34