Can I prevent Sinatra / Rack from reading the entire request block into memory?

Let's say I have a Sinatra ala route:

put '/data' do
  request.body.read
  # ...
end

It seems that the entire request.body is being read into memory. Is there a way to consume the body when it enters the system, instead of pre-fueling it in Rack / Sinatra?

I see that I can do this to read the body in parts, but the whole body still seems to be read in memory in advance.

put '/data' do
  while request.body.read(1024) != nil 
    # ...
  end
  # ...
end
+3
source share
1 answer

You cannot avoid this at all without fixing Sinatra and / or Rack. This is done Rack::Requestwhen called by Sinatra to create .request.POST params

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
+3

Source: https://habr.com/ru/post/1749701/


All Articles