99from __future__ import print_function
1010
1111import re
12-
12+ import random
1313import cache
1414import adapter .cheat_sheets
1515import adapter .cmd
@@ -106,10 +106,52 @@ def _get_page_dict(self, query, topic_type, request_options=None):
106106 """
107107 Return answer_dict for the `query`.
108108 """
109-
110109 return self ._adapter [topic_type ]\
111110 .get_page_dict (query , request_options = request_options )
112111
112+ def handle_if_random_request (self , topic ):
113+ """
114+ Check if the `query` if a :random one, if yes we check its correctness and then randomly select a topic, based on the provided prefix.
115+
116+ """
117+
118+ def __select_random_topic (prefix , topic_list ):
119+ #Here we remove the special cases
120+ cleaned_topic_list = [ x for x in topic_list if '/' not in x and ':' not in x ]
121+
122+ #Here we still check that cleaned_topic_list in not empty
123+ if not cleaned_topic_list :
124+ return prefix
125+
126+ random_topic = random .choice (cleaned_topic_list )
127+ return prefix + random_topic
128+
129+ if topic .endswith ('/:random' ) or topic .lstrip ('/' ) == ':random' :
130+ #We strip the :random part and see if the query is valid by running a get_topics_list()
131+ if topic .lstrip ('/' ) == ':random' :
132+ topic = topic .lstrip ('/' )
133+ prefix = topic [:- 7 ]
134+
135+ topic_list = [x [len (prefix ):]
136+ for x in self .get_topics_list ()
137+ if x .startswith (prefix )]
138+
139+ if '' in topic_list :
140+ topic_list .remove ('' )
141+
142+ if topic_list :
143+ # This is a correct formatted random query like /cpp/:random as the topic_list is not empty.
144+ random_topic = __select_random_topic (prefix , topic_list )
145+ return random_topic
146+ else :
147+ # This is a wrongly formatted random query like /xyxyxy/:random as the topic_list is empty
148+ # we just strip the /:random and let the already implemented logic handle it.
149+ wrongly_formatted_random = topic [:- 8 ]
150+ return wrongly_formatted_random
151+
152+ #Here if not a random requst, we just forward the topic
153+ return topic
154+
113155 def get_answer_dict (self , topic , request_options = None ):
114156 """
115157 Find cheat sheet for the topic.
@@ -120,7 +162,8 @@ def get_answer_dict(self, topic, request_options=None):
120162 Returns:
121163 answer_dict: the answer dictionary
122164 """
123-
165+
166+ topic = self .handle_if_random_request (topic )
124167 topic_type = self .get_topic_type (topic )
125168
126169 # 'question' queries are pretty expensive, that's why they should be handled
0 commit comments