DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations

Trending

  • MLOps: Definition, Importance, and Implementation
  • Multi-Stream Joins With SQL
  • DevOps Pipeline and Its Essential Tools
  • The Native Way To Configure Path Aliases in Frontend Projects

Generating and Streaming Potentially Large CSV Files Using Ruby on Rails

S M  Sohan user avatar by
S M Sohan
·
Oct. 11, 13 · Interview
Like (0)
Save
Tweet
Share
12.50K Views

Join the DZone community and get the full member experience.

Join For Free

Most applications I’ve worked on at some point required an ‘Export’ feature, so people would be able to play with the data using the familiar Excel interface. I’m sharing some code here from a recent work that did the following:

Generate a CSV file for download with up to 100,000 rows in it. Since the contents of the file depend on some dynamic parameters, and the underlying data is changing all the time, the file must be generated live. Generating a large file takes time, and the load balancer will drop the connection if it takes more than 1 minute. In fact, as a consumer, I myself would be frustrated had it taken even 1 minute to see something happening. This problem natually requires a streaming solution.

For a familiar example, let’s say we are downloading a CSV file containing transactions on an online store for the accounting folks. Lets say the URL is as follows:

http://transactions.com/transactions.csv?start=2013-01-01&end=2013-04-30&type=CreditCard&min_amount=400

So, this would download a file containing the transactions from January to April of 2013, where a CreditCard was used for a purchase over $400. Here goes the code example with inline comments describing interesting parts.

class Transaction
  belongs_to :store
  attr_accessible :time, :amount

  def self.csv_header
    #Using ruby's built-in CSV::Row class
    #true - means its a header
    CSV::Row.new([:time, :store, :amount], ['Time', 'Store', 'Amount'], true)
  end

  def to_csv_row
    CSV::Row.new(title: title, store: store.name, amount: amount)
  end

  def self.find_in_batches(filters, batch_size, &block)
    #find_each will batch the results instead of getting all in one go
    where(filters).find_each(batch_size: batch_size) do |transaction|
      yield transaction
    end
  end

end

Given this Transaction model, the controller can call the methods and set appropriate http headers to stream the rows as they are generated instead of waiting for the whole file to be generated. Here’s the example controller code:

class TransactionsController

  def index

    respond_to do |format|

      format.csv render_csv

    end

  end

  private

  def render_csv
    set_file_headers
    set_streaming_headers

    response.status = 200

    #setting the body to an enumerator, rails will iterate this enumerator
    self.response_body = csv_lines(filters)
  end


  def set_file_headers
    file_name = "transactions.csv"
    headers["Content-Type"] = "text/csv"
    headers["Content-disposition"] = "attachment; filename=\"#{file_name}\""
  end


  def set_streaming_headers
    #nginx doc: Setting this to "no" will allow unbuffered responses suitable for Comet and HTTP streaming applications
    headers['X-Accel-Buffering'] = 'no'

    headers["Cache-Control"] ||= "no-cache"
    headers.delete("Content-Length")
  end

  def csv_lines

    Enumerator.new do |y|
      y << Transaction.csv_header.to_s

      #ideally you'd validate the params, skipping here for brevity
      Transaction.find_in_batches(params){ |transaction| y << transaction.to_csv_row.to_s }
    end

  end

end

As you see in this example, it’s pretty straightforward once you put the pieces together. These streaming headers work under most servers including Passenger, Unicorn, etc. but webrick doesn’t support streaming responses. It took me some time to figure out the headers and the enumerator thing, but since then it’s working beautifully for us. Hopefully it will help someone with a similar need.



CSV

Published at DZone with permission of S M Sohan, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • MLOps: Definition, Importance, and Implementation
  • Multi-Stream Joins With SQL
  • DevOps Pipeline and Its Essential Tools
  • The Native Way To Configure Path Aliases in Frontend Projects

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: