MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / get_subreddit_data

Function get_subreddit_data

web_programming/reddit.py:25–56  ·  view source on GitHub ↗

subreddit : Subreddit to query limit : Number of posts to fetch age : ["new", "top", "hot"] wanted_data : Get only the required data in the list

(
    subreddit: str, limit: int = 1, age: str = "new", wanted_data: list | None = None
)

Source from the content-addressed store, hash-verified

23
24
25def get_subreddit_data(
26 subreddit: str, limit: int = 1, age: str = "new", wanted_data: list | None = None
27) -> dict:
28 """
29 subreddit : Subreddit to query
30 limit : Number of posts to fetch
31 age : ["new", "top", "hot"]
32 wanted_data : Get only the required data in the list
33 """
34 wanted_data = wanted_data or []
35 if invalid_search_terms := ", ".join(sorted(set(wanted_data) - valid_terms)):
36 msg = f"Invalid search term: {invalid_search_terms}"
37 raise ValueError(msg)
38 response = httpx.get(
39 f"https://www.reddit.com/r/{subreddit}/{age}.json?limit={limit}",
40 headers={"User-agent": "A random string"},
41 timeout=10,
42 )
43 response.raise_for_status()
44 if response.status_code == 429:
45 raise httpx.HTTPError(response=response)
46
47 data = response.json()
48 if not wanted_data:
49 return {id_: data["data"]["children"][id_] for id_ in range(limit)}
50
51 data_dict = {}
52 for id_ in range(limit):
53 data_dict[id_] = {
54 item: data["data"]["children"][id_]["data"][item] for item in wanted_data
55 }
56 return data_dict
57
58
59if __name__ == "__main__":

Callers 1

reddit.pyFile · 0.85

Calls 2

jsonMethod · 0.80
getMethod · 0.45

Tested by

no test coverage detected