Send CSV in Body via Falcon

1.3k views Asked by At

I'm trying to send CSV via GET request in Falcon. I don't know where to begin.

Below is my code:

class LogCSV(object):
"""CSV generator.

This class responds to  GET methods.
"""
def on_get(self, req, resp):
    """Generates CSV for log."""

    mylist = [
        'one','two','three'
    ]

    myfile = open("testlogcsv.csv", 'w')
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    wr.writerow(mylist)

    resp.status = falcon.HTTP_200
    resp.content_type = 'text/csv'
    resp.body = wr

I don't want spoonfeeding, please let me know what I should read/watch to help solve this. Thanks

1

There are 1 answers

0
lbenitez000 On

You should use the Response.stream attribute. It must be set to a file-like object (an object with a read() method) before returning.

So first, you should write your CSV to this object, and then give it to Falcon. In your case:

resp.content_type = 'text/csv'
# Move the file pointer to the beginning
myfile.seek(0)
resp.stream = myfile

Remember to move the file pointer to the beginning using seek(0) , so Falcon can read it.

If your file is ephemeral and small enough to be stored in memory, you can use a memory-file like BytesIO instead of a normal file. It behaves like a normal file but is never written to the file system.

myfile = BytesIO()
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)

...

resp.content_type = 'text/csv'
# Move the file pointer to the beginning
myfile.seek(0)
resp.stream = myfile

;)