-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathget_stream.py
More file actions
60 lines (47 loc) · 1.71 KB
/
Copy pathget_stream.py
File metadata and controls
60 lines (47 loc) · 1.71 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
59
60
import argparse
import json
import os
import ssl
import sys
import requests
from dotenv import load_dotenv
load_dotenv(verbose=True) # Throws error if it can't find .env file
# Argparse for cli options. Run `python engagement_totals.py -h` to see list of available arguments.
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--chunksize", type=int, help="Overrides default chunksize of '10000'.")
args = parser.parse_args()
USERNAME = os.getenv("USERNAME")
PASSWORD = os.getenv("PASSWORD")
ACCOUNT_NAME = os.getenv("ACCOUNT_NAME")
ENDPOINT_LABEL = os.getenv("POWERTRACK_LABEL")
domain = "https://gnip-stream.twitter.com/stream"
endpoint = f"{domain}/powertrack/accounts/{ACCOUNT_NAME}/publishers/twitter/{ENDPOINT_LABEL}.json"
headers = {
'connection': "keep-alive",
'accept': 'application/json',
'Accept-Encoding': 'gzip',
'gnipkeepalive': '30',
}
def main():
if args.chunksize:
chunksize = args.chunksize
else:
chunksize = 10000
timeout = 0
# Reconnect logic with exponential backoff
while True:
get_stream(endpoint, chunksize)
time.sleep(2 ** timeout)
timeout += 1
def get_stream(endpoint, chunksize):
response = requests.get(url=endpoint, auth=(USERNAME, PASSWORD), stream=True, headers=headers)
for chunk in response.iter_content(chunksize, decode_unicode=True): # Content gets decoded
if "\n" or "\r" in chunk: # Handles keep-alive new lines
print(chunk) # Prints keep-alive signal to stdout
else:
try:
print(json.loads(chunk))
except ValueError:
sys.stderr.write(f"Error processing JSON: {ValueError} {chunk}\n")
if __name__ == '__main__':
main()