首页 > 解决方案 > Getting data from flask request is slow

问题描述

I have a device sending POSTs to my server. In python, I grab the posted data using either:

request.data
request.get_data
request.get_json

But the times I can getting for these simple data gets varies. I test with something like this:

start = time.time()
resp = request.data
return str(time.time() - start)

From some end nodes, I see times of sub 1ms, and some, I see over 100ms, for the same amount of data. Since the request object is already created, and I assume the data is already received, what contributes to this variance in speed?

标签: pythonflaskrequest

解决方案


我假设数据已经收到

不要假设:)

Flask 使用来自 Werkzeug 的请求类,它调用get_data. get_data要么已经缓存了数据,要么读取了流

文档字符串中甚至还有一个警告:

通常不先检查内容长度就调用此方法是个坏主意,因为客户端可能会发送数十兆字节或更多字节,从而导致服务器出现内存问题。

如果您想安全地避免在缓慢的请求上阻塞您的服务器,您应该在它前面放置一些反向代理(nginx?),它可以更有效地处理输入,并在准备好时将完整的请求交给服务器。


推荐阅读