在生成Ruby时,如何通过HTTParty上传数据?

发布于 2025-01-17 20:07:07 字数 700 浏览 4 评论 0原文

我有一个生成一些数据的函数。现在,该数据已写入文件。文件完成后,我通过 HTTParty 上传它:

require 'httparty'

url = "..."

def generate_data(file)
  file << "First line of data\n"
  sleep 1
  file << "Second line of data\n"
  sleep 1
  file << "Third line of data\n"
end

File.open('payload.txt', 'w+') do |file|
  generate_data(file)
  file.rewind
  HTTParty.post(url, body: {file: file})
end

碰巧,generate_data 需要一点时间 - 我想加速脚本避免通过交错写入磁盘数据的生成并上传。我如何使用 HTTParty 来做到这一点?

我一直在寻找类似 StringIO 的东西,它可以用作固定大小的 FIFO 缓冲区:generate_data 函数写入它(并在缓冲区满时阻塞),而HTTParty.post 调用从中读取。 (当缓冲区为空时阻塞)。然而,我没有找到类似的东西。

I have a function which generates some data. Right now, this data is written to a file. Once the file is complete, I upload it via HTTParty:

require 'httparty'

url = "..."

def generate_data(file)
  file << "First line of data\n"
  sleep 1
  file << "Second line of data\n"
  sleep 1
  file << "Third line of data\n"
end

File.open('payload.txt', 'w+') do |file|
  generate_data(file)
  file.rewind
  HTTParty.post(url, body: {file: file})
end

As it happens, generate_data takes a bit -- I would like to accelerate the script and avoid writing to disk by interleaving the generation of the data and uploading it. How could I do this using HTTParty?

I was looking for something like StringIO which could be used as a fixed-size FIFO buffer: the generate_data function writes to it (and blocks when the buffer is full) while the HTTParty.post call reads from it. (and blocks when the buffer is empty). However, I failed to find anything like that.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

慈悲佛祖 2025-01-24 20:07:07

您需要使用流媒体

HTTParty.put(
  'http://localhost:3000/train',
  body_stream: StringIO.new('foo')
)

You need to use streaming

HTTParty.put(
  'http://localhost:3000/train',
  body_stream: StringIO.new('foo')
)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文