如何使用ActionController::Live从MongoDB下载CSV数据?

9
我已经在控制器中创建了一个 CSV 下载器,代码如下:
format.csv do
  @records  = Model.all

  headers['Content-Disposition'] = "attachment; filename=\"products.csv\"" 
  headers['Content-Type'] ||= 'text/csv'
end

现在我想创建“服务器推送事件(server sent events)”以便从中下载CSV文件以进行优化。 我知道可以在Rails中使用ActionController :: Live实现此目的,但我没有相关经验。
请有人告诉我如何:
1.批量查询记录 2.将记录添加到“流”中 3.处理来自浏览器端的SSE 4.将记录写入CSV文件
如果我的任何假设都是错误的,请纠正我。帮助我更好地完成这个任务。谢谢。
2个回答

0

Mongoid会自动分批查询您的记录(更多信息请参见此处

要将您的记录添加到CSV文件中,您应该执行以下操作:

records = MyModel.all
# By default batch_size is 100, but you can modify it using .batch_size(x)

result = CSV.generate do |csv|
  csv << ["attribute1", "attribute2", ...]
  records.each do |r|
    csv << [r.attribute1, r.attribute2, ...]
  end
end

send_data result, filename: 'MyCsv.csv'

记住send_data是一个ActionController方法!


0

我认为你不需要使用SSE来生成CSV。只需将include ActionController::Live包含在控制器中,然后使用response.stream.write迭代你的集合即可:

include ActionController::Live
...
def some_action
  format.csv do
    # Needed for streaming to workaround Rack 2.2 bug
    response.headers['Last-Modified'] = Time.now.httpdate

    headers['Content-Disposition'] = "attachment; filename=\"products.csv\""
    headers['Content-Type'] ||= 'text/csv'

    [1,2,3,4].each do |i|   # --> change it to iterate your DB records
      response.stream.write ['SOME', 'thing', "interesting #{i}", "#{Time.zone.now}"].to_csv

      sleep 1  # some fake delay to see chunking
    end

    ensure
      response.stream.close
    end
  end

使用curl或类似工具尝试逐行查看输出:

$ curl -i  http://localhost:3000/test.csv

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接