Check if the `query` is a :random one, if yes we check its correctness and then randomly select a topic, based on the provided prefix.
(self, topic)
| 119 | ) |
| 120 | |
| 121 | def handle_if_random_request(self, topic): |
| 122 | """ |
| 123 | Check if the `query` is a :random one, |
| 124 | if yes we check its correctness and then randomly select a topic, |
| 125 | based on the provided prefix. |
| 126 | |
| 127 | """ |
| 128 | |
| 129 | def __select_random_topic(prefix, topic_list): |
| 130 | # Here we remove the special cases |
| 131 | cleaned_topic_list = [ |
| 132 | x for x in topic_list if "/" not in x and ":" not in x |
| 133 | ] |
| 134 | |
| 135 | # Here we still check that cleaned_topic_list in not empty |
| 136 | if not cleaned_topic_list: |
| 137 | return prefix |
| 138 | |
| 139 | random_topic = random.choice(cleaned_topic_list) |
| 140 | return prefix + random_topic |
| 141 | |
| 142 | if topic.endswith("/:random") or topic.lstrip("/") == ":random": |
| 143 | # We strip the :random part and see if the query is valid by running a get_topics_list() |
| 144 | if topic.lstrip("/") == ":random": |
| 145 | topic = topic.lstrip("/") |
| 146 | prefix = topic[:-7] |
| 147 | |
| 148 | topic_list = [ |
| 149 | x[len(prefix) :] for x in self.get_topics_list() if x.startswith(prefix) |
| 150 | ] |
| 151 | |
| 152 | if "" in topic_list: |
| 153 | topic_list.remove("") |
| 154 | |
| 155 | if topic_list: |
| 156 | # This is a correct formatted random query like /cpp/:random as the topic_list is not empty. |
| 157 | random_topic = __select_random_topic(prefix, topic_list) |
| 158 | return random_topic |
| 159 | else: |
| 160 | # This is a wrongly formatted random query like /xyxyxy/:random as the topic_list is empty |
| 161 | # we just strip the /:random and let the already implemented logic handle it. |
| 162 | wrongly_formatted_random = topic[:-8] |
| 163 | return wrongly_formatted_random |
| 164 | |
| 165 | # Here if not a random request, we just forward the topic |
| 166 | return topic |
| 167 | |
| 168 | def get_answers( |
| 169 | self, topic: str, request_options: Dict[str, str] = None |
no test coverage detected