gpt4 book ai didi

ruby - 使用 rest-client 将文件下载到磁盘而不首先将其全部加载到内存中

转载 作者:IT王子 更新时间:2023-10-28 23:35:37 27 4
gpt4 key购买 nike

我正在使用 rest-client 下载大页面(大小约为 1.5 GB)。检索到的值存储在内存中,而不是保存到文件中。结果我的程序因 failed to allocate memory (NoMemoryError) 而崩溃。

但是没有必要将这些数据保存在内存中,甚至可以直接保存到磁盘中。

我发现“您可以:(...) 手动处理响应(例如,将其作为流进行操作,而不是将其全部读入内存)有关更多信息,请参阅 RestClient::Request 的文档。”在 https://github.com/rest-client/rest-client不幸读了http://www.rubydoc.info/gems/rest-client/1.7.3/RestClient/Request我不知道它是如何实现的。

我也知道我可能会使用其他库 (Using WWW:Mechanize to download a file to disk without loading it all in memory first),但我的程序已经在使用 rest-client。

简化代码:

data = RestClient::Request.execute(:method => :get, :url => url, :timeout => 3600)
file = File.new(filename, 'w')
file.write data
file.close

代码 - https://github.com/mkoniecz/CartoCSSHelper/blob/395deab626209bcdafd675c2d8e08d0e3dd0c7f9/downloader.rb#L126

最佳答案

另一种方法是使用 raw_response。这会直接保存到文件中,通常在 /tmp 中,并且可以毫无问题地处理重定向。见 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"

关于ruby - 使用 rest-client 将文件下载到磁盘而不首先将其全部加载到内存中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29010275/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com