Turning array into a downloadable blob

I have an array of results from an external database which I display to the screen in a table just fine.

I want to offer a download of that data as a CSV.

Can I turn the result array (of dicts) into a downloadable “document” object that I could write to a data tables table as a blob and access via a link?

I think writing each row to a data table seems like overkill; could be hundreds of them, thousands even.

I just can’t get my head around it. I seem to have a blind spot for this.

Ok, with the help of this post I worked it out.
I basically serialised the array and created a blob of it, like this example :

  
  # Some dummy data.
  a = []
  for i in range(30):
    a.append({
      "ddi":i*1000,
      "calls":i+10,
      "mins":i*10*i-1
    })
    
  # serialise it for the sake of blobbing it.
  s = ""
  for d in a:
    s += str(d['ddi'])+","+str(d['calls'])+","+str(d['mins'])+"\n"
  
  # Blob it
  o=anvil.BlobMedia("text/csv",s)

Not sure how this scales to larger files, so any better ideas would be welcomed.

1 Like

This is exactly how I would do it - although you’re right that you might run into memory issues for larger files. At that point you could consider temporary files on the filesystem or something, but I would really cross that bridge when you come to it.

1 Like