Django SJISのCSVをダウンロードさせるビュー基底クラス

Django
2017-05-09 17:49 (7年前) ytyng
View in English

Django SJISのCSVをダウンロードさせるビュー基底クラス

# -*- coding: utf-8 -*-

from __future__ import unicode_literals, print_function

import csv
import io
from django.http import HttpResponse
from django.views.generic import View


class CsvExportViewBase(View):
output_as_sjis = True

def get(self, *args, **kwargs):
if self.output_as_sjis:
return self._get_response_as_sjis(*args, **kwargs)

response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = \
'attachment; filename={}'.format(self.get_filename())
writer = csv.writer(response)

for r in self.get_result_rows():
writer.writerow(r)
return response

def _get_response_as_sjis(self, *args, **kwargs):
response = HttpResponse(content_type='text/csv; charset=Shift-JIS')
response['Content-Disposition'] = \
'attachment; filename={}'.format(self.get_filename())
sio = io.StringIO()
writer = csv.writer(sio)

for r in self.get_result_rows():
writer.writerow(r)

response.write(sio.getvalue().encode(encoding='cp932'))
return response

def get_connection(self):
from django.db import connection
return connection

def get_cursor(self):
connection = self.get_connection()
return connection.cursor()

def get_sql(self):
"""
Implement required.
"""
return "SELECT NOW()"

def get_sql_args(self):
return []

def row_filter(self, row):
return row

def get_result_rows(self):

cursor = self.get_cursor()

cursor.execute(self.get_sql(), *self.get_sql_args())

# Header
yield self.row_filter(f[0] for f in cursor.description)

# Content
for r in cursor.fetchall():
yield self.row_filter(r)

def get_filename(self):
return "items.csv"

現在未評価
タイトルとURLをコピー

コメント

アーカイブ

2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011