Django重置某些请求的连接

时间:2017-06-15 08:17:40

标签: python django

我存在的问题是,当向Django服务器发送一些请求时,它会在时间之前关闭连接。

这是Github上的simple project

以下是没有正文的简单POST请求的工作原理: enter image description here

但是当我发送一些大小约为15MB的二进制数据时,Postmen会显示连接错误: enter image description here

curl 可以正常使用

curl -X POST -d "@bin/ngrok" localhost:3000/test/

我认为这是邮差中的一些错误,但在移动设备上它也不起作用;

我尝试比较请求标头。我试图折腾middeware。我试着调试Djnago代码。但我可以找到解决方案。你能帮我解决这个问题吗?

更新1

在settings.py文件中设置

FILE_UPLOAD_MAX_MEMORY_SIZE = 1000 * 1000 * 1000
DATA_UPLOAD_MAX_MEMORY_SIZE = 1000 * 1000 * 1000

无法解决问题

更新2

我在 index 方法中添加了行print(len(request.body))

@csrf_exempt
def index(request):
    print(len(request.body))

    return HttpResponse("Hello")

现在它有效。但为什么我要将机构提交给完整的请求呢? 在我的真实项目中,我检查身份验证令牌,如果它是错误的,我没有从正文中读取内容。

2 个答案:

答案 0 :(得分:1)

Yup, I can reproduce this with your repo.

I took a look with Wireshark, and it looks like the Django devserver is actually responding before the entire payload has been sent. I'm not sure what the HTTP spec says about whether this is okay or not, but it's obvious some client libraries (that used by Postman and your mobile device) deem this an error, while others like libcurl are okay with it.

When you add print(len(request.body)), it forces Django (and the underlying stack) to consume the entire body in order to figure out its length before outputting the response.

This behavior also occurs when running the app under uwsgi, for what it's worth.

The TCP stream looks like this in Wireshark: enter image description here

答案 1 :(得分:0)

几个星期前,我在Heroku的一个项目中遇到了完全相同的问题。 Heroku日志显示不太有用的服务器请求中断'错误。经过几天的调试并查看django源代码,我发现它与django's Upload Handlers有关。

有一个名为FILE_UPLOAD_MAX_MEMORY_SIZE的设置,默认为2.5Mb。小于此设置的任何上载都将由MemoryFileUploadHandler(在内存中)处理,否则TemporaryFileUploadHandler负责文件处理。我从来没有发现原因,但在Heroku上,TemporaryFileUploadHandler总是使我的应用程序崩溃。我通过将设置增加到客户端要上传的最大文件大小来创建了一种解决方法。