Q:

Best way to Create a CSV, Compress it and Attatch with Email

I have a Question, I am searching for a best way to perform following tasks. 

Create In-Memory csv file 
Compress it (Gizip, or Zip)
Attach it with the email

I am having hard time find out the exact solution which i am looking for.  
here is my code. 
code
prospects = Customer.objects.filter(state_id=2)
csvfile = StringIO.StringIO()
writer = UnicodeWriter(csvfile, encoding='utf-8')
writer.writerow(["Name", "Email"])
for prospect in prospects:
    writer.writerow(
        [prospect.name, prospect.email]
    )
csvobj = csvfile.getvalue() # not sure about it.  

Code Part 2
g = gzip. GzipFile(fileobj=csvobj)
g.close()

Code Part 3
  msg = EmailMultiAlternatives(
            subject="Innovation",
            body="text_context",
            from_email=settings. DEFAULT_FROM_EMAIL,
            to=["bac@gmail.com"]
        )
  msg.attach("z.gzip",g, 'application/zip')
  msg.send(True)

Error
TypeError: 'GzipFile' object does not support indexing

A:

Here's how I'd do it. 
import StringIO
import tablib

headers = ["name", "Email"]
values = Customer.objects.filter(state_id=2).values_list(‘name’, ‘email’)
data = tablib. Dataset(*values, headers=headers)

csvfile = StringIO.StringIO()
csvfile.write(data.csv)

gzipped = gzip. GzipFile(mode='wb', fileobj=csvfile.getvalue())
gzipped.close()

# msg stuff...
msg.attach("z.gzip", gzipped, 'application/zip')

Works fine for me, do you still get an error if you try that?