django-render-csv

utilities to render csv in django


Keywords
django, response, csv, utilities
License
Other
Install
pip install django-render-csv==0.2.4

Documentation

django-render-csv

utilities to render csv for django

Code

import csv
from django.http import HttpResponse

def render_csv(data, filename="data.csv"):
    res = HttpResponse(content_type='text/csv')
    res['Content-Disposition'] = 'attachment; filename="%s"' % filename

    writer = csv.writer(res)
    for item in data:
        writer.writerow(item)

    return res

def as_csv(fn=None, filename=None):
    def decorator(fn):
        def _fn(request, *args, **kwargs):
            data = fn(request, *args, **kwargs)
            return render_csv(data, filename=filename)

        return _fn

    return decorator(fn) if fn else decorator

Install

$ pip install django-render-csv

Usage

from django_render_csv import render_csv, as_csv

def csv(request):
    return render_csv([
        'a', 'b', 'c',
        '1', '2', '3'
    ], filename="filename.csv")

@as_csv(filename="filename.csv")
def csv_with_decorator(request):
    return [
        'a', 'b', 'c',
        '1', '2', '3'
    ]