我可以让Sinatra/Rack不将整个请求正文读入内存吗? [英] Can I have Sinatra / Rack not read the entire request body into memory?
问题描述
说我有一条Sinatra路线ala:
put '/data' do
request.body.read
# ...
end
似乎整个request.body被读入内存.有什么方法可以消耗掉进入系统的身体,而不是事先将它们全部缓冲在Rack/Sinatra中?
我知道我可以这样做以读取身体的各个部分,但是似乎仍会事先将整个身体读入内存中.
put '/data' do
while request.body.read(1024) != nil
# ...
end
# ...
end
如果不修补Sinatra和/或Rack,通常无法避免此问题.当 request.POST
被Sinatra称为 创建 params
. /p>
但是您可以在Sinatra前面放置一个中间件来删除主体:
require 'sinatra'
require 'stringio'
use Rack::Config do |env|
if env['PATH_INFO'] == '/data' and env['REQUEST_METHOD'] == 'PUT'
env['rack.input'], env['data.input'] = StringIO.new, env['rack.input']
end
end
put '/data' do
while request.env['data.input'].body.read(1024) != nil
# ...
end
# ...
end
Say I have a Sinatra route ala:
put '/data' do
request.body.read
# ...
end
It appears that the entire request.body is read into memory. Is there a way to consume the body as it comes into the system, rather than having it all buffered in Rack/Sinatra beforehand?
I see I can do this to read the body in parts, but the entire body still seems to be read into memory beforehand.
put '/data' do
while request.body.read(1024) != nil
# ...
end
# ...
end
You cannot avoid this in general without patching Sinatra and/or Rack. It is done by Rack::Request
when request.POST
is called by Sinatra to create params
.
But you could place a middleware in front of Sinatra to remove the body:
require 'sinatra'
require 'stringio'
use Rack::Config do |env|
if env['PATH_INFO'] == '/data' and env['REQUEST_METHOD'] == 'PUT'
env['rack.input'], env['data.input'] = StringIO.new, env['rack.input']
end
end
put '/data' do
while request.env['data.input'].body.read(1024) != nil
# ...
end
# ...
end
这篇关于我可以让Sinatra/Rack不将整个请求正文读入内存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!