Skip to content

Commit 721f586

Browse files
committed
docs and tweaks
1 parent 28f8db1 commit 721f586

9 files changed

+303
-98
lines changed

leetcode/configuration.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -24,14 +24,14 @@ def dump_key(self, key, value):
2424
with open(self.path, 'w') as yaml_file:
2525
yaml.dump(self.data, yaml_file, default_flow_style=False)
2626

27-
def execute(self, args):
27+
def _execute(self, args):
2828
if args.config_key not in self.data['user_data']:
2929
print(f"Invalid key: {args.config_key}")
3030
return
3131
else:
3232
if getattr(args, 'config_key') and getattr(args, 'config_value'):
3333
self.dump_key(args.config_key, args.config_value)
34-
print('Configuration updated successfully.')
34+
print('[green]Configuration updated successfully.')
3535

3636
def check_session_response(session_id: str) -> bool:
3737
QUERY = """ query
@@ -76,8 +76,6 @@ def check_session_validity(path = CONFIG_PATH) -> bool:
7676
The default session_id is taken from the configuration file. """
7777

7878
class Configuration():
79-
session_checked = False
80-
8179
def __init__(self, session_id: str = ''):
8280
self.host = 'https://leetcode.com'
8381
self.user_config = UserConfig()
@@ -92,10 +90,8 @@ def __init__(self, session_id: str = ''):
9290
'Referer': self.host}
9391
self._cookies: dict = {'csrftoken': self._csrf_cookie,
9492
'LEETCODE_SESSION': self.session_id}
95-
if not Configuration.session_checked:
96-
self.__check_session_validity()
9793

98-
def __check_session_validity(self):
94+
def check_session_validity(self):
9995
QUERY = """ query
10096
{
10197
user {

leetcode/main.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import argparse
22

33
# from leetcode.models import *
4-
from leetcode.configuration import UserConfig, check_session_validity
4+
from leetcode.configuration import UserConfig
55
from leetcode.models.graphql_problemset_question_list import \
66
ProblemsetQuestionList
77
from leetcode.models.graphql_question_of_today import QuestionOfToday
@@ -17,6 +17,7 @@
1717
# TODO: problem with import in synced code or code to submit
1818
# TODO: random problem selector (from not accepted problems)
1919
# TODO: check the changes in question_content and apply them to the code in other files
20+
# TODO: use config without having to have a session
2021

2122
def positive_integer(value):
2223
try:
@@ -87,5 +88,4 @@ def main():
8788

8889

8990
if __name__ == '__main__':
90-
if check_session_validity():
91-
main()
91+
main()

leetcode/models/graphql_problemset_question_list.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def __init__(self, filters={}, limit=None, skip=0):
7878

7979
self.data = None
8080

81-
def fetch_data(self, parameters: Dict = None) -> QueryResult:
81+
def fetch_data(self, parameters: Dict) -> QueryResult:
8282
""" Fetches the data from the LeetCode API.
8383
Updates the state of the object.
8484

leetcode/models/graphql_question_content.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ def __init__(self, title_slug: str = None):
1919
if title_slug is not None:
2020
self.fetch_data(self.title_slug)
2121

22-
def fetch_data(self, title_slug: str = None) -> Dict:
22+
def fetch_data(self, title_slug) -> Dict:
2323
""" Fetches the content data for the problem.
2424
2525
Args:

leetcode/models/graphql_question_info_table.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,15 @@ def __init__(self, title_slug: str = None):
4747
if title_slug is not None:
4848
self.fetch_data(self.title_slug)
4949

50-
def fetch_data(self, title_slug: str = None) -> Dict:
50+
def fetch_data(self, title_slug) -> Dict:
51+
""" Fetches the question data for the given title slug.
52+
53+
Args:
54+
title_slug (str, optional): The title slug of the question to fetch data for.
55+
If provided the data is fetched when the object is created. Defaults to None.
56+
57+
Returns:
58+
Dict: The question data for the given title slug. {id , title, difficulty, status, categoryTitle}"""
5159
try:
5260
with Loader('Fetching question details...', ''):
5361
if title_slug is not None and title_slug != self.title_slug:
@@ -69,7 +77,7 @@ def fetch_data(self, title_slug: str = None) -> Dict:
6977
console.print(f"{e.__class__.__name__}: {e}", style=ALERT)
7078
sys.exit(1)
7179

72-
def format_table(self, data: Question):
80+
def format_table(self, data: Question) -> LeetTable:
7381
""" Formats the given question data into a LeetTable object.
7482
7583
Args:
@@ -93,7 +101,7 @@ def format_table(self, data: Question):
93101

94102
return table
95103

96-
def show(self):
104+
def show(self) -> None:
97105
""" Displays the question data in a LeetTable.
98106
99107
If the data has not been fetched yet, an exception is raised.
@@ -104,7 +112,7 @@ def show(self):
104112
else:
105113
raise Exception("Data is not fetched yet.")
106114

107-
def __rich_console__(self, console: Console, options):
115+
def __rich_console__(self, console: Console, options) -> Table:
108116
""" Returns a Rich Table object for console output.
109117
110118
Raises:

leetcode/models/graphql_submission_list.py

Lines changed: 60 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -35,14 +35,16 @@ class SubmissionList(QueryTemplate):
3535
def __init__(self):
3636
super().__init__()
3737
# Instance specific variables
38-
self.question_id: int = None
3938
self.show_terminal: bool = False
4039
self.submission_download: bool = False
4140

42-
self.data = None
43-
self.params = {'offset': 0, 'limit': 20, 'lastKey': None, 'questionSlug': None}
41+
self._question_id: int = None
42+
self._data = None
43+
self._params = {'offset': 0, 'limit': 20, 'lastKey': None, 'questionSlug': None}
44+
self._data_fetched: bool = False
4445

45-
def fetch_data(self, question_id: int = None) -> Dict:
46+
def fetch_data(self, question_id) -> Dict:
47+
# TODO: make the parameters usable
4648
""" Fetches the submission list data for the problem.
4749
4850
Args:
@@ -55,16 +57,20 @@ def fetch_data(self, question_id: int = None) -> Dict:
5557
with Loader('Fetching submission list...', ''):
5658
if question_id is not None and question_id != self.question_id:
5759
self.question_id = question_id
58-
self.params['questionSlug'] = ProblemInfo.get_title_slug(self.question_id)
60+
61+
if self.data_fetched:
62+
return self.data
5963

6064
graphql_query = GraphQLQuery(self.query, self.params)
6165
response = self.leet_API.post_query(graphql_query)
62-
return response['data']
66+
self.data = QuestionSubmisstionList.from_dict(response['data'])
67+
self.data_fetched = True
68+
return self.data
6369
except Exception as e:
6470
console.print(f"{e.__class__.__name__}: {e}", style=ALERT)
6571
sys.exit(1)
6672

67-
def _execute(self, args):
73+
def _execute(self, args) -> None:
6874
""" Executes the query with the given arguments and displays the result.
6975
7076
Args:
@@ -88,7 +94,7 @@ def _execute(self, args):
8894
except Exception as e:
8995
console.print(f"{e.__class__.__name__}: {e}", style=ALERT)
9096

91-
def show(self):
97+
def show(self) -> None:
9298
""" Displays the query result in a table. """
9399

94100
table = LeetTable()
@@ -105,7 +111,7 @@ def show(self):
105111
console.print(table)
106112

107113
@staticmethod
108-
def fetch_accepted(submissions):
114+
def fetch_accepted(submissions) -> QuestionSubmisstionList.Submission:
109115
""" Fetches the latest accepted submission from the list of submissions.
110116
111117
Args:
@@ -115,7 +121,7 @@ def fetch_accepted(submissions):
115121
Submission: The latest accepted submission. If no accepted submissions are found, None is returned."""
116122
return next((x for x in submissions if x.statusDisplay == 'Accepted'), None)
117123

118-
def show_code(self):
124+
def show_code(self) -> None:
119125
""" Displays the code of the latest accepted submission.
120126
121127
If no accepted submissions are found, an exception is raised. """
@@ -140,7 +146,7 @@ def show_code(self):
140146
except Exception as e:
141147
console.print(f"{e.__class__.__name__}: {e}", style=ALERT)
142148

143-
def download_submission(self):
149+
def download_submission(self) -> None:
144150
""" Downloads the code of the latest accepted submission.
145151
146152
If no accepted submissions are found, an exception is raised.
@@ -166,7 +172,7 @@ def download_submission(self):
166172
except Exception as e:
167173
console.print(f"{e.__class__.__name__}: {e}", style=ALERT)
168174

169-
def __parse_args(self, args):
175+
def __parse_args(self, args) -> None:
170176
""" Parses the arguments passed to the query.
171177
172178
Args:
@@ -181,5 +187,46 @@ def __parse_args(self, args):
181187
if getattr(args, 'download'):
182188
self.submission_download = True
183189

190+
@property
191+
def data(self):
192+
return self._data
193+
194+
@data.setter
195+
def data(self, data: Dict):
196+
self._data = data
197+
198+
@property
199+
def params(self):
200+
return self._params
201+
202+
@params.setter
203+
def params(self, params: Dict):
204+
self._params = params
205+
self.data_fetched = False
206+
207+
@property
208+
def data_fetched(self):
209+
return self._data_fetched
210+
211+
@data_fetched.setter
212+
def data_fetched(self, data_fetched: bool):
213+
self._data_fetched = data_fetched
184214

185-
215+
@property
216+
def question_id(self):
217+
return self._question_id
218+
219+
@question_id.setter
220+
def question_id(self, question_id: int):
221+
self._question_id = question_id
222+
self.data_fetched = False
223+
self.params['questionSlug'] = ProblemInfo.get_title_slug(self.question_id)
224+
225+
226+
if __name__ == '__main__':
227+
submissions = SubmissionList()
228+
submissions.fetch_data(6536534)
229+
submissions.show()
230+
231+
submissions.fetch_data(2)
232+
submissions.show()

0 commit comments

Comments
 (0)