From f1b5b8105073bc76b0fbfcc4b3bd69b095d6dfd5 Mon Sep 17 00:00:00 2001 From: Kumi Date: Mon, 19 Aug 2024 17:33:35 +0200 Subject: [PATCH] fix: improve search input validation and error handling Added validation to ensure both language and project are selected before proceeding with the search. Redirects to the homepage if the query is empty. Enhanced error handling in index redirect function to catch invalid project/language combinations and inform users appropriately. Resolves issues with user experience and input handling. --- src/wikimore/app.py | 22 +++++++++++++++++++++- src/wikimore/templates/base.html | 2 +- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/wikimore/app.py b/src/wikimore/app.py index e97187d..463171c 100644 --- a/src/wikimore/app.py +++ b/src/wikimore/app.py @@ -171,6 +171,17 @@ def search() -> Union[Text, Response]: query = request.form["query"] lang = request.form["lang"] project = request.form["project"] + + if not lang or not project: + return render_template( + "article.html", + title="Error", + content="Please select a language and a project.", + ) + + if not query: + return redirect(url_for("index_php_redirect", project=project, lang=lang)) + return redirect( url_for("search_results", project=project, lang=lang, query=query) ) @@ -400,7 +411,16 @@ def index_php_redirect(project, lang) -> Response: """ # TODO: Handle query string - url = f"{app.languages[lang]['projects'][project]}/w/api.php?action=query&format=json&meta=siteinfo&siprop=general" + try: + url = f"{app.languages[lang]['projects'][project]}/w/api.php?action=query&format=json&meta=siteinfo&siprop=general" + except KeyError: + return ( + render_template( + "article.html", + title="Project does not exist", + content=f"Sorry, the project {project} does not exist in the {lang} language.", + ), + ) with urllib.request.urlopen(url) as response: data = json.loads(response.read().decode()) main_page = data["query"]["general"]["mainpage"] diff --git a/src/wikimore/templates/base.html b/src/wikimore/templates/base.html index ebb3de7..0614922 100644 --- a/src/wikimore/templates/base.html +++ b/src/wikimore/templates/base.html @@ -20,7 +20,7 @@ {% endfor %} - +