作爲一種更乾淨的方法,您可以註冊一個渲染器。
在您的配置設置,添加:
config.add_renderer(name='csv',
factory='mypackage.renderers.CSVRenderer')
然後在mypackage/renderers.py
:
@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
}
:
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()
之後,你可以與渲染裝飾你的看法這種方法的優點是更好的可測試視圖代碼(您只需檢查字典值S,不需要解析任何東西),你還可以添加一個XLS或任何渲染到了同樣的觀點:
@view_config(..., renderer='xls')
@view_config(..., renderer='csv')
def myview(self):
...
++ HTTP 101 FTW – 2012-04-02 16:55:24