想要提示浏览器保存csv

时间:2012-04-02 09:28:05

标签: python pyramid

想要提示浏览器使用pyramid.response.Response搜索线索来保存csv,并在此处找到a link Django答案,但我无法使用它与Pyramid wsgi我的代码如下所示:

from pyramid.response import Response
def get_list_names_emails(request):
    session, env = request.db, request.client_env
    response = Response(content_type='text/csv')
    output = StringIO()
    writer = csv.writer(output)
    writer.writerow(['SomeName', 'SomeEmail', 'CompanyName])
    csv_output = output.getvalue()
    return csv_output

3 个答案:

答案 0 :(得分:15)

作为一种更简洁的方法,您可以注册渲染器。

在配置设置中,添加:

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

然后在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()

之后,您可以使用渲染器修饰视图:

@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
            }

这种方法的优点是更好的可测试视图代码(您只需检查字典值,无需解析任何内容),您还可以将XLS或任何渲染器添加到同一视图中:

@view_config(..., renderer='xls')
@view_config(..., renderer='csv')
def myview(self):
    ...

答案 1 :(得分:9)

尝试添加内容处理:

response['Content-Disposition'] = 'attachment; filename="report.csv"'

答案 2 :(得分:3)

最好设置内容类型

response['Content-type'] = 'text/csv'
response['Content-Disposition'] = 'attachment; filename="report.csv"'