-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path2-recurse.py
executable file
·50 lines (42 loc) · 1.38 KB
/
2-recurse.py
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
#!/usr/bin/python3
"""
Queries the Reddit API recursively and returns
a list containing the titles of all hot articles
for a given subreddit. If no results are found for
the given subreddit, return None.
"""
from requests import get
from sys import argv
def recurse(subreddit: str, hot_list=[], after="", count=0) -> list:
"""
Function to recurcively query a subreddit
And return the hot topics for the subreddit
Args:
subreddit (str): The subreddit to query
hot_list (list): Doesn't have to be passed
after (str): Doesn't have to be passed
count (int): Doesn't have to be passed
"""
request_url = "https://www.reddit.com/r/{}/hot/.json".format(subreddit)
headers = {
"User-Agent": "I'll use a Real user Agent next I promise"
}
query_strings = {
"after": after,
"count": count,
"limit": 100
}
response = get(request_url, headers=headers, params=query_strings,
allow_redirects=False)
if response.status_code == 404:
return None
results = response.json()['data']
after = results['after']
count += results['dist']
for child in results["children"]:
hot_list.append(child["data"]["title"])
if after is not None:
return recurse(subreddit, hot_list, after, count)
return hot_list
if __name__ == "__main__":
print(recurse(argv[1]))