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

(Comments)

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"

Currently unrated

Comments

Recent Tweets

  • ytyng

    ytyng @ytyng

    なおってた
    2 days, 15 hours ago

  • ytyng

    ytyng @ytyng

    vuetify って2になって、グリッドのタグ名がBootstrapと同じになったのね。v-flex と書かなくてよくなってた。良い。
    2 days, 16 hours ago

  • ytyng

    ytyng @ytyng

    YahooショッピングのAPI、応答を返さない状態じゃない? https://t.co/rYKTlr7RcU
    2 days, 19 hours ago

Recent Posts

Archive

2020
2019
2018
2017
2016
2015
2014
2013
2012
2011

Categories

Authors

Feeds

RSS / Atom