hug icon indicating copy to clipboard operation
hug copied to clipboard

Example showing how to implement CSV output format

Open dazzag24 opened this issue 7 years ago • 3 comments

Has anyone got some sample code showing how to achieve this?

Thanks

dazzag24 avatar Feb 15 '18 15:02 dazzag24

Have a look at:

  • http://www.hug.rest/website/learn/output_formats
  • https://github.com/hugapi/hug/issues/793
import csv
import io

# ...

@hug.format.content_type('text/csv')
def format_as_csv(data, request=None, response=None):
    output = io.StringIO()
    writer = csv.writer(output)
    for row in data:
        writer.writerow(row)
    return output.getvalue().encode('utf8')

@hug.get('/csv', output=format_as_csv)
def get_csv():
    # ...
    response.set_header('Content-Disposition', 'attachment; filename={your-file-name.ext}')

frafra avatar Sep 16 '19 15:09 frafra

Have a look at:

import csv
import io

# ...

@hug.format.content_type('text/csv')
def format_as_csv(data, request=None, response=None):
    output = io.StringIO()
    writer = csv.writer(output)
    for row in data:
        writer.writerow(row)
    return output.getvalue().encode('utf8')

@hug.get('/csv', output=format_as_csv)
def get_csv():
    # ...
    response.set_header('Content-Disposition', 'attachment; filename={your-file-name.ext}')

Your answer is valuable, but I don't know why "response.set_header" can be called in get_csv() , in my attempt I get the error "NameError: name 'response' is not defined". @frafra

primary-student avatar Jun 13 '22 03:06 primary-student

@primary-student I think my function definition is wrong, as response is not defined indeed. If you look at the first link I posted, you see some examples where the function has response as one of the arguments. I think it should look like this:

def get_csv(data, request, response):

I have not tested it :)

frafra avatar Jun 13 '22 09:06 frafra