我正在使用 Rest-client 下载大页面(大小约为 1.5 GB)。检索到的值存储在内存中,而不是保存到文件中。结果我的程序崩溃了failed to allocate memory (NoMemoryError)
.
但没有必要将这些数据保存在内存中,甚至可以直接保存到磁盘中。
我发现“您可以:(...)手动处理响应(例如,将其作为流进行操作,而不是将其全部读入内存)有关更多信息,请参阅 RestClient::Request 的文档。”在https://github.com/rest-client/rest-client https://github.com/rest-client/rest-client遗憾的是读完之后http://www.rubydoc.info/gems/rest-client/1.7.3/RestClient/Request http://www.rubydoc.info/gems/rest-client/1.7.3/RestClient/Request我不知道如何实现它。
我也知道我可能会使用其他库(使用 WWW:Mechanize 将文件下载到磁盘,而不先将其全部加载到内存中 https://stackoverflow.com/questions/4360043/using-wwwmechanize-to-download-a-file-to-disk-without-loading-it-all-in-memory)但我的程序已经在使用rest-client。
简化代码:
data = RestClient::Request.execute(:method => :get, :url => url, :timeout => 3600)
file = File.new(filename, 'w')
file.write data
file.close
Code - https://github.com/mkoniecz/CartoCSSHelper/blob/395deab626209bcdafd675c2d8e08d0e3dd0c7f9/downloader.rb#L126 https://github.com/mkoniecz/CartoCSSHelper/blob/395deab626209bcdafd675c2d8e08d0e3dd0c7f9/downloader.rb#L126
另一种方法是使用raw_response
。这会直接保存到文件中,通常在/tmp
并毫无问题地处理重定向。
看流式响应 https://github.com/rest-client/rest-client#streaming-responses。这是他们的例子:
>> raw = RestClient::Request.execute(
method: :get,
url: 'http://releases.ubuntu.com/16.04.2/ubuntu-16.04.2-desktop-amd64.iso',
raw_response: true)
=> <RestClient::RawResponse @code=200, @file=#<Tempfile:/tmp/rest-client.20170522-5346-1pptjm1>, @request=<RestClient::Request @method="get", @url="http://releases.ubuntu.com/16.04.2/ubuntu-16.04.2-desktop-amd64.iso">>
>> raw.file.size
=> 1554186240
>> raw.file.path
=> "/tmp/rest-client.20170522-5346-1pptjm1"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)