Coverage for an_website/quotes/generator.py: 70.968%
31 statements
« prev ^ index » next coverage.py v7.6.4, created at 2024-11-16 19:56 +0000
« prev ^ index » next coverage.py v7.6.4, created at 2024-11-16 19:56 +0000
1# This program is free software: you can redistribute it and/or modify
2# it under the terms of the GNU Affero General Public License as
3# published by the Free Software Foundation, either version 3 of the
4# License, or (at your option) any later version.
5#
6# This program is distributed in the hope that it will be useful,
7# but WITHOUT ANY WARRANTY; without even the implied warranty of
8# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9# GNU Affero General Public License for more details.
10#
11# You should have received a copy of the GNU Affero General Public License
12# along with this program. If not, see <https://www.gnu.org/licenses/>.
14"""Generate quotes and authors for users to make their own wrong quotes."""
16from __future__ import annotations
18import random
20from ..utils.request_handler import APIRequestHandler
21from .utils import (
22 Author,
23 Quote,
24 QuoteReadyCheckHandler,
25 get_authors,
26 get_quotes,
27 get_wrong_quotes,
28)
31def get_authors_and_quotes(count: int) -> tuple[list[Author], list[Quote]]:
32 """Get random batch of authors and quotes."""
33 if count < 1:
34 return [], []
36 authors: list[Author] = list(get_authors(shuffle=True)[:count])
37 quotes: list[Quote] = list(get_quotes(shuffle=True)[:count])
39 if len(authors) <= 1 or len(quotes) <= 1:
40 return authors, quotes
42 wrong_quote = get_wrong_quotes(lambda wq: wq.rating > 0, shuffle=True)[0]
44 if (wq_author := wrong_quote.author) not in authors:
45 authors[random.randrange(0, len(authors))] = wq_author # nosec: B311
47 if (wq_quote := wrong_quote.quote) not in quotes:
48 quotes[random.randrange(0, len(quotes))] = wq_quote # nosec: B311
50 return authors, quotes
53class QuoteGenerator(QuoteReadyCheckHandler):
54 """The request handler for the quote generator HTML page."""
56 async def get(self, *, head: bool = False) -> None:
57 """Handle GET requests."""
58 count = self.get_int_argument("count", 5, min_=0, max_=10)
59 authors, quotes = get_authors_and_quotes(count)
60 if head:
61 return
62 await self.render(
63 "pages/quotes/generator.html", authors=authors, quotes=quotes
64 )
67class QuoteGeneratorAPI(APIRequestHandler, QuoteReadyCheckHandler):
68 """The request handler for the quote generator API."""
70 async def get(self, *, head: bool = False) -> None:
71 """Handle GET requests."""
72 count = self.get_int_argument("count", 5, min_=0, max_=10)
73 authors, quotes = get_authors_and_quotes(count)
74 if head:
75 return
76 await self.finish_dict(
77 count=count,
78 authors=[author.to_json() for author in authors],
79 quotes=[quote.to_json() for quote in quotes],
80 )