eggDiscover / followerslookup / views.py

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
import datetime
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger


class TwitterUserListView(ListView):
    """
    this class return all TwitterUsers and statics about their followers
    """
    def get_context_data(self,**kwargs):
        """
        this function return extra data to the context.
        In this case it returns statics about the users following each twitter user
        """
        context = super(TwitterUserListView,self).get_context_data(**kwargs)
        for twitter_user in  context['object_list']:
            users = User.objects.filter(twitteruser = twitter_user)
            twitter_user.count = users.count()
            # filter users with no picture
            twitter_user.eggs = users.filter(
                profile_image_url__contains = "default_profile",
                statuses_count = 0,
                description = None
                ).count() / float(twitter_user.count)*100
            
        return context
    
class TwitterUserDetailView(DetailView):
    """
    This class return detailed information about a Twitter User.
    In this case it return the twitter_user name and a list of followers 
    detected as eggs :

    - no profile picture
    
    - no tweets emited

    - no description
    
    """
    
    def get_context_data(self,**kwargs):
        """
        This function return all the eggs of a TwitterUser
        """
        context = super(TwitterUserDetailView,self).get_context_data(**kwargs)
        users = User.objects.filter(twitteruser = context['object'])
        eggs = users.filter(
                profile_image_url__contains = "default_profile",
                statuses_count = 0,
                description = None,
                friends_count__lte = 5
                )
        paginator = Paginator(eggs,100)
        page = self.request.GET.get('page')
        try:
            eggs = paginator.page(page)
        except TypeError:
            # If page is not an integer, deliver first page.
            eggs = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            eggs = paginator.page(paginator.num_pages)
        context['object'].eggs = eggs 
        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):
        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)
            

            result = convert_context_to_csv.delay(context['object_list'],csv_file = path)
            return HttpResponse(
        """
            requested file will be generated on our server. Find it when it will 
            be ready at <a href="/media/%s/">/media/%s/</a>
        """%(self.kwargs['user'],self.kwargs['user'])
                )
                                  
                                                              
        return self.get_csv_response(convert_context_to_csv(context['object_list']))

    
    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
    
        
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.