Source

eggDiscover / followerslookup / tasks.py

Full commit
from celery.schedules import crontab
from celery.decorators import task
from celery.decorators import periodic_task
from social_auth.models import UserSocialAuth
from followerslookup.authentication import get_account
from followerslookup.fetching import get_followers_infos,get_followers_ids
from followerslookup.models import TwitterUser, User
import csv,codecs
try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO


@task()
def fetch():
    user = UserSocialAuth.objects.all()[0]
    account = get_account(user)
    for user in TwitterUser.objects.all():
        followers_ids = get_followers_ids(account, user.name)
        followers_infos = get_followers_infos(account, followers_ids,user.name )
    return 'Fetch ended'

@task()
def convert_context_to_csv(context, csv_file = StringIO()):
    if type(csv_file) == unicode:
        csv_file = open("%s%s"%(csv_file,'-users.csv'),"w")
    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:
        csv_file.close()
        return
    return csv_file.getvalue()