hug
hug copied to clipboard
Example showing how to implement CSV output format
Has anyone got some sample code showing how to achieve this?
Thanks
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}')
Have a look at:
- http://www.hug.rest/website/learn/output_formats
- Change file name returned when using
hug.output_format.file#793import 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 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 :)