I'm working on a project where I need to get all followers from a specific user and store this info in a database. I have done this and so far it suits my needs, but I'd like to make it more "professional" and would love to hear your suggestions.
The first code is twitter.py and the 2nd one is app.py
import requests
class TwitterAPI():
def __init__(self):
with open('token.ini') as ini:
self.token = ini.readline()
def get_follower(self, action, **kwargs):
params = kwargs.keys()
if 'user_id' not in params and 'screen_name' not in params:
raise TypeError('Incorrect parameters, expecting `user_id` or `screen_name`')
url = {
'list': 'https://api.twitter.com/1.1/followers/ids.json',
'info': 'https://api.twitter.com/1.1/users/show.json'
}
r = requests.get(
url[action],
params = kwargs,
headers = {'Authorization': 'Bearer ' + self.token},
)
return r.json() if r.status_code == 200 else r.status_code
import twitter
import sqlite3
from datetime import datetime
conn = sqlite3.connect('twitter_analytics.sqlite3')
c = conn.cursor()
api = twitter.TwitterAPI()
followers = api.get_follower(action='list', screen_name='Croves')
c.execute("INSERT INTO user(twitter_screen_name, created_at) VALUES(?, ?)", ('Croves', datetime.now()))
conn.commit()
user_id = c.lastrowid
for count, follower in enumerate(followers['ids']):
info = api.get_follower(action='info', user_id=follower)
c.execute("""
INSERT INTO user_followers(user_id, id_str, name, screen_name, location, url, description, protected, verified, followers_count, friends_count, profile_banner_url, profile_image_url_https, created_at)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (
user_id,
info.get('id_str'),
info.get('name'),
info.get('screen_name'),
info.get('location'),
info.get('url'),
info.get('description'),
info.get('protected'),
info.get('verified'),
info.get('followers_count'),
info.get('friends_count'),
info.get('profile_banner_url'),
info.get('profile_image_url_https'),
datetime.now()
))
if count % 10 == 0:
conn.commit()
conn.commit()
conn.close()