Skip to content

Commit c7294ae

Browse files
committed
Refactor get_thread to get all posts from specific page
1 parent 10cc7f6 commit c7294ae

File tree

1 file changed

+32
-21
lines changed

1 file changed

+32
-21
lines changed

loading_api_wrapper/api.py

Lines changed: 32 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import math
2+
13
import requests
24

35
API_URL = "https://api.loading.se"
@@ -82,39 +84,48 @@ def get_post(self, post_id):
8284

8385
return response.json()
8486

85-
def get_thread(self, thread_id):
87+
def get_thread(self, thread_id, page=None):
8688
"""Returns post data if the id belongs to a thread start."""
8789

8890
if not thread_id:
8991
return {"code": 404, "message": '"thread_id" is not allowed to be empty'}
9092

9193
url = f"{API_URL}/{API_VERSION}/posts/{thread_id}"
9294
headers = {"User-Agent": USER_AGENT}
95+
96+
# Chooses a specific page instead of the first page which is the default page.
97+
if page and page > 1:
98+
headers["page"] = str(page)
99+
93100
response = requests.get(url, headers=headers)
94101

95-
if response.status_code == 200:
96-
post_data = response.json()
97-
parent_post = post_data["posts"][-1]
98-
parent_user = None
102+
if response.status_code != 200:
103+
return response.json()
99104

100-
# Only thread starts has a title so anything else is a regular post.
101-
if "title" in parent_post:
102-
for user in post_data["users"]:
103-
if user["id"] == parent_post["userId"]:
104-
parent_user = user
105-
break
105+
data = response.json()
106106

107+
if "title" not in data["posts"][-1]:
108+
return {
109+
"code": response.status_code,
110+
"message": "Exists, but was not a thread id",
111+
}
112+
113+
# Doing this checks to make sure it only return data from a page that exists.
114+
if page:
115+
replies = data["posts"][-1]["replies"]
116+
pages = math.ceil(replies / 30)
117+
118+
# There is always atleast one page.
119+
if pages == 0:
120+
pages = 1
121+
122+
# Page is out of range.
123+
if page < 1 or page > pages:
107124
return {
108125
"code": response.status_code,
109-
"post": {
110-
"posts": [parent_post],
111-
"users": [parent_user],
112-
},
113-
}
114-
else:
115-
return {
116-
"code": response.status_code,
117-
"message": "Exists, but was not a thread id",
126+
"post": {"posts": [], "users": []},
118127
}
119128

120-
return response.json()
129+
successful_response = {"code": response.status_code, "post": data}
130+
131+
return successful_response

0 commit comments

Comments
 (0)