I'm trying to find my bug or any potential bottleneck that cause my program to be really slow. The script is to get all the followers and friends and save that in MongoDB.
import pymongo
import tweepy
consumer_key = ''
consumer_secret = ''
access_token = ''
access_token_secret = ''
from pymongo import MongoClient
client = MongoClient()
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, retry_count=3, retry_delay=60)
db = client.tweets
raw_tweets = db.raw_tweets
users = db.users
def is_user_in_db(user_id):
return get_user_from_db(user_id) != None
def get_user_from_db(user_id):
return users.find_one({'user.id' : user_id})
def get_user_from_twitter(user_id):
return api.get_user(user_id)
def get_followers(user_id):
users = []
page_count = 0
for user in tweepy.Cursor(api.followers, id=user_id, count=200).pages():
page_count += 1
print 'Getting page {} for followers'.format(page_count)
users.extend(user)
return users
def get_friends(user_id):
users = []
page_count = 0
for user in tweepy.Cursor(api.friends, id=user_id, count=200).pages():
page_count += 1
print 'Getting page {} for friends'.format(page_count)
users.extend(user)
return users
def get_followers_ids(user_id):
ids = []
page_count = 0
for page in tweepy.Cursor(api.followers_ids, id=user_id, count=5000).pages():
page_count += 1
print 'Getting page {} for followers ids'.format(page_count)
ids.extend(page)
return ids
def get_friends_ids(user_id):
ids = []
page_count = 0
for page in tweepy.Cursor(api.friends_ids, id=user_id, count=5000).pages():
page_count += 1
print 'Getting page {} for friends ids'.format(page_count)
ids.extend(page)
return ids
def process_user(user):
user_id = user['id']
screen_name = user['screen_name']
print 'Processing user : {}'.format(user['screen_name'])
the_user = get_user_from_db(user_id)
if the_user is None:
follower_ids = get_followers_ids(user['screen_name'])
friend_ids = get_friends_ids(user['screen_name'])
user['followers_ids'] = follower_ids
user['friends_ids'] = friend_ids
users_to_add = []
for follower in get_followers(screen_name):
if not is_user_in_db(follower.id):
users_to_add.append(follower._json)
for friend in get_friends(screen_name):
if not is_user_in_db(friend.id):
users_to_add.append(friend._json)
users.insert_many(users_to_add)
users.insert_one(doc['user'])
if __name__ == "__main__":
for doc in raw_tweets.find({'processed' : {'$exists': False}}):
print 'Start processing'
if 'user' in doc:
process_user(doc['user'])
if 'retweeted_status' in doc:
process_user(doc['retweeted_status']['user'])
raw_tweets.update_one({'_id': doc['_id']}, {'$set':{'processed':True}})