Want to prompt browser to save csv

后端 未结 3 859
终归单人心
终归单人心 2021-02-10 10:04

Want to prompt browser to save csv using pyramid.response.Response searched for clues and found here\'s a link Django answer but i can\'t use it with Pyramid wsgi my code looks

相关标签:
3条回答
  • 2021-02-10 10:08

    Try adding Content-Disposition:

    response['Content-Disposition'] = 'attachment; filename="report.csv"'
    
    0 讨论(0)
  • 2021-02-10 10:19

    As a cleaner way to do that, you can register a renderer.

    In your configuration set-up, add:

        config.add_renderer(name='csv',
                            factory='mypackage.renderers.CSVRenderer')
    

    then in mypackage/renderers.py:

    class CSVRenderer(object):
        def __init__(self, info):
            pass
    
        def __call__(self, value, system):
            fout = StringIO.StringIO()
            writer = csv.writer(fout, delimiter=';', quoting=csv.QUOTE_ALL)
    
            writer.writerow(value['header'])
            writer.writerows(value['rows'])
    
            resp = system['request'].response
            resp.content_type = 'text/csv'
            resp.content_disposition = 'attachment;filename="report.csv"'
            return fout.getvalue()
    

    After that, you can decorate your view with the renderer:

    @view_config(..., renderer='csv')
    def myview(self):
        header = ['name', 'surname', 'address']
    
        rows = [
                (
                    row['name'],
                    row['surname'],
                    row['address'],
                )
            for row in query_rows(.....)
            ]
    
        return {
                'header': header,
                'rows': rows
                }
    

    The advantage of this approach is better testable view code (you just check for the dictionary values, no need to parse anything) and you can also add a XLS or whatever renderer to the same view:

    @view_config(..., renderer='xls')
    @view_config(..., renderer='csv')
    def myview(self):
        ...
    
    0 讨论(0)
  • 2021-02-10 10:30

    It's better to set content type as well

    response['Content-type'] = 'text/csv'
    response['Content-Disposition'] = 'attachment; filename="report.csv"'
    
    0 讨论(0)
提交回复
热议问题