forked from anthonydb/python-snippets
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwitter-api-sqlite-old.py
More file actions
58 lines (49 loc) · 1.61 KB
/
twitter-api-sqlite-old.py
File metadata and controls
58 lines (49 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# DEPRECATED // Uses old Twitter API that is deprecated.
# Fetch Twitter profile details from Twitter API into a SQLite DB
import requests
import sqlite3
import os
from datetime import datetime
# These are the accounts for which you will fetch data
handles_list = [
'anthonydb',
'nytimes',
'capitalweather',
'washingtonpost',
'usatoday'
]
# The base url for the Twitter API
base_url = 'https://api.twitter.com/1/users/show.json?screen_name='
# Function to add a row to the twaccounts table in your SQLite DB
def insert_db(handle, followers, description):
conn = sqlite3.connect('social_data.db')
cur = conn.cursor()
cur.execute('''
INSERT INTO twaccounts VALUES (?,?,?,?);
''', (datetime.now(), handle, followers, description))
conn.commit()
conn.close()
# Create the SQLite database if it doesn't exist
if not os.path.exists('social_data.db'):
conn = sqlite3.connect('social_data.db')
conn.close()
else:
pass
# Create the DB table if it's not there already
conn = sqlite3.connect('social_data.db')
cur = conn.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS twaccounts
(FetchDate Date, Handle Text, Followers Integer, Description Text)
''')
conn.commit()
conn.close()
# Iterate over user handles and hit the API with each
for user in handles_list:
url = base_url + user + '&include_entities=true'
print 'Fetching @' + user
response = requests.get(url)
profile = response.json()
handle = profile['screen_name']
followers = profile['followers_count']
description = profile['description']
insert_db(handle, followers, description)