Source

eggDiscover / followerslookup / views.py

from models import User, TwitterUser
from django.views.generic import ListView
from django.http import HttpResponse
from django.conf import settings
import csv,codecs
import os
try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO


    

class CsvGenericListView(ListView):
    def get_queryset(self):
        qs = User.objects.all()
        if "user" in self.kwargs:
            qs = qs.filter(twitteruser__name = self.kwargs["user"])
        
        for k, v in self.request.GET.iteritems():
            print k,v
            if k == "order_by":
                qs = qs.order_by(v)
            elif k == 'description__isnull':
                if v == "false":
                    qs = qs.exclude(description = None).filter(description__isnull = False)
                if v == "true":
                    qs = qs.filter(description = None)
            elif k == 'picture':
                if v == 'false':
                    qs = qs.filter(profile_image_url__contains = "default_profile")
                if v == 'true':
                    qs = qs.exclude(profile_image_url__contains = "default_profile")
            elif k == "page":
                pass
            else:
                qs = qs.filter((k,v))
        return qs

    def render_to_response(self,context):
        if "complete" in self.kwargs :
            filename_list = []
            for k,v in self.request.GET.iteritems():
                filename_list.append(k)
                filename_list.append(v)
                
            relative_path = '-'.join(filename_list)
            base_path = '/%s/%s/'%(settings.MEDIA_ROOT,self.kwargs['user'])
            path = base_path+relative_path
            if not os.path.exists(base_path):
                     os.makedirs(base_path)
            
            csv_file = open("%s%s"%(path,'-user.csv'),"w")
            self.get_csv_response(self.convert_context_to_csv(context,csv_file = csv_file))
            csv_file.close()
            return HttpResponse("requested file : %s will be generated on our server"%self.kwargs['user'])
                                  
                                                              
        return self.get_csv_response(self.convert_context_to_csv(context))

        
    
    def get_csv_response(self, content, **httpresponse_kwargs):
        "Construct an `HttpResponse` object."
        resp = HttpResponse(content,
                            content_type='text/csv',
                            **httpresponse_kwargs)
        resp['Content-Disposition'] = 'attachment; filename=users.csv'
        return resp
    def convert_context_to_csv(self, context, csv_file = StringIO()):
        writer = csv.writer(csv_file)
        writer.writerow(User._meta.get_all_field_names())
        for obj in context["object_list"]:
            row = []
            for elem in User._meta.get_all_field_names():
                if elem == "twitteruser":
                    twitter_users = []
                    for usr in obj.twitteruser_set.all():
                        twitter_users.append(usr.name)
                    row.append(','.join(twitter_users))
                else:
                    row.append(unicode(getattr(obj,elem)).encode("utf-8"))
            writer.writerow(row)
        if type(csv_file) == file:
            return
        return csv_file.getvalue()