想提示浏览器保存csv [英] Want to prompt browser to save csv

查看:40
本文介绍了想提示浏览器保存csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想提示浏览器使用 pyramid.response.Response 搜索线索并找到这里的 一个链接 Django 的回答,但我不能将它与 Pyramid wsgi 一起使用,我的代码如下所示:

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 like this:

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

推荐答案

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

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')

然后在 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
            }

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

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):
    ...

这篇关于想提示浏览器保存csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆