Source

eggDiscover / followerslookup / views.py

Full commit
from models import User, TwitterUser
from django.views.generic import ListView,DetailView
from django.http import HttpResponse
from django.conf import settings
import os
from tasks import convert_context_to_csv

class TwitterUserDetailView(DetailView):
    
    def get_context_data(self,**kwargs):
        context = super(TwitterUserDetailView,self).get_context_data(**kwargs)
        avg = GenericListViewMixin()
        avg.kwargs, avg.request = self.kwargs, self.request
        avg.kwargs['user'] = TwitterUser.objects.get(pk = self.kwargs['pk']).name
        # count number of users
        extra_queryset = avg.get_queryset()
        context['count'] = extra_queryset.count()
        # count users without picture
        context['nopicture'] = "%i %%"%(
            (float(
                extra_queryset.filter(
                    profile_image_url__contains = "default_profile"
                    ).count()
                ) / float(context['count'])
                ) * 100
            )
        context['notweet'] ="%i %%"%(
            float(
                extra_queryset.filter(statuses_count = 0).count() / float(context['count'])
                                                                            )
                                                                            *100)
        return context

class GenericListViewMixin(object):
    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


class CsvGenericListView(GenericListViewMixin, ListView):

    def render_to_response(self,context):
        print self.kwargs
        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)
            

            convert_context_to_csv.delay(context,csv_file = path)
            return HttpResponse(
        """
            requested file will be generated on our server. Find it when it will 
            be ready at <a href=%s>%s</a>
        """%(settings.MEDIA_URL+relative_path,settings.MEDIA_URL+relative_path)
                )
                                  
                                                              
        return self.get_csv_response(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()