INPRO: Bugfixing and better returns

This commit is contained in:
2023-06-04 15:30:59 -07:00
parent a88774fc5b
commit 6c5717c4d1
5 changed files with 98 additions and 39 deletions
+18 -5
View File
@@ -1,5 +1,5 @@
# app.py # app.py
from flask import Flask, request, jsonify, send_file, render_template, redirect from flask import Flask, request, jsonify, send_file, render_template, redirect, Response
import random import random
from datetime import date, datetime, timedelta # used for daily verse from datetime import date, datetime, timedelta # used for daily verse
import sqlite3 import sqlite3
@@ -212,6 +212,8 @@ def parse_query(query_override:str = None):
query = query_override query = query_override
if query: if query:
query = query.strip() query = query.strip()
if request.args.get("view", "rich") != "rich":
return jsonify({"Error":"/find endpoint only supports rich responses"})
logging.info(f"Query: {query}") logging.info(f"Query: {query}")
if not query: if not query:
return send_file("html/find.html") return send_file("html/find.html")
@@ -434,7 +436,7 @@ def page_not_found(e):
@app.get("/<shortcode>") @app.get("/<shortcode>")
def idx(shortcode=''): def idx(shortcode=''):
if not sanity: if not sanity:
return("There is an issue with permissions. Check log, or please notify tyler@dinsmoor.us") return("Sanity check failed. Check log, or please notify tyler@dinsmoor.us")
if shortcode: if shortcode:
return resolve_shortcode(shortcode) return resolve_shortcode(shortcode)
logging.info("Index Served") logging.info("Index Served")
@@ -477,6 +479,17 @@ def verse_of_the_day():
response = jsonify(response_list) response = jsonify(response_list)
logging.debug(f"Search Response: {response}") logging.debug(f"Search Response: {response}")
return response return response
def make_view(response_list=[]):
#TODO: Maybe use flask session to make this easier to deal with
# https://stackoverflow.com/a/53152394
arg_view = request.args.get("view", None)
if arg_view == "plain":
response = "<br>".join(response_list)
elif arg_view == "rich":
response = "<br>".join(response_list)
else:
response = jsonify(response_list)
@app.get("/search") @app.get("/search")
def search(): def search():
keywords = request.args.get("kw", None) keywords = request.args.get("kw", None)
@@ -504,9 +517,9 @@ def search():
response = jsonify(response_list) response = jsonify(response_list)
logging.debug(f"Search Response: {response}") logging.debug(f"Search Response: {response}")
return response return response
@app.get("/reader") @app.get("/browse")
def bible_reader(): def bible_reader():
return send_file("html/reader.html") return render_template("reader.html", books=cached.get("book_names"))
# We should return an index of all books with # We should return an index of all books with
# drop down menus of each chapter, and a search # drop down menus of each chapter, and a search
# bar at the top for quick seeking, which can use # bar at the top for quick seeking, which can use
@@ -667,7 +680,7 @@ def resolve_shortcode(shortcode: str = ""):
logging.info(f"Resolved Shortcode {shortcode} for query '{query}'") logging.info(f"Resolved Shortcode {shortcode} for query '{query}'")
return redirect(f"/find?kw={query}&view=rich") return redirect(f"/find?kw={query}&view=rich")
if __name__ == "__main__": if __name__ == "__main__":
print("You must run this program within a uwsgi environment if you are running this for multiple users.") print("You must run this program within a uwsgi environment if you are running this for multiple users.")
print("Otherwise, you may end up with database corruption if multiple writes happen.") print("Otherwise, you may end up with database corruption if multiple writes happen.")
+7
View File
@@ -0,0 +1,7 @@
<table id="Books">
{% for book in books %}
<tr>
<td><a href="/find?kw={{ book[0] }}&view=rich">{{ book[0] }}</a></td>
</tr>
{% endfor %}
</table>
+5
View File
@@ -0,0 +1,5 @@
<form action="/plan">
<input type="text" name="kw" value="{query}" id="searchBar">
<input type="submit" value="Search">
<input type="hidden" name="view" value="rich">
</form>
+33 -34
View File
@@ -7,14 +7,7 @@ from os import stat, getuid
def check_sanity(): def check_sanity():
check_database_permissions() check_database_permissions()
check_random()
check_verse_of_the_day()
check_find()
check_define()
check_search()
check_show()
check_seq()
check_shortcode()
def check_database_permissions(): def check_database_permissions():
dependancies = ['data/seq.db', "data/shortcodes.db"] dependancies = ['data/seq.db', "data/shortcodes.db"]
@@ -22,35 +15,41 @@ def check_database_permissions():
for dependancy in dependancies: for dependancy in dependancies:
if stat(dependancy).st_uid != current_uid: if stat(dependancy).st_uid != current_uid:
raise PermissionError(dependancy) raise PermissionError(dependancy)
def check_random():
#TODO: Ensure random returns a verse
pass
def check_verse_of_the_day(): def check_queries(url=None):
#TODO: Ensure VOTD returns a verse, the same, at least twice try:
pass import requests
except ImportError:
raise ImportError("You must install the requests python3 module")
endpoints: list = 'show find search seq status votd random define'.split(" ")
viewarguments: list = 'rich plain json'.split(" ")
with open("tools/search_keywords.txt") as f:
keywords = f.read().splitlines()
def check_find(): log = []
#TODO: Ensure that a varaity of queries don't cause an error (need to define a few)
pass
def check_define(): baseurl = "http://localhost:1611"
#TODO: Ensure a few words that are in the dictionary (and those that are not) and those misspelled, give correct responses if url:
pass baseurl = url
def check_search(): for endpoint in endpoints:
#TODO: Ensure that blanket searches with different syntaxes resolve correctly for viewargument in viewarguments:
pass for keyword in keywords:
testurl = f"{baseurl}/{endpoint}?view={viewargument}&kw={keyword}"
r = requests.get(testurl)
log.append([testurl, r.status_code])
def check_show(): with open("tools/sanity_results.txt", 'r+') as logfile:
#TODO: Ensure that many types of verse syntaxes correctly resolve. for logged in log:
pass if logged[1] != 200:
logfile.write(f"{logged[1]} - {logged[0]}\n")
def check_seq(): if __name__ == "__main__":
#TODO: Begin a new sequence and check that it does not give us an error import argparse
pass parser = argparse.ArgumentParser("Endpoint testing for your kjv api.")
parser.add_argument('url', type=str, nargs='?', help="like http://localhost:1611")
def check_shortcode(): args = parser.parse_args()
#TODO: make a new shortcode for a search and then try to resolve it. if not args.url:
pass print("Trying default http://localhost:1611")
url = "http://localhost:1611"
check_queries(url=args.url)
+35
View File
@@ -0,0 +1,35 @@
Genesis 1
Genesis1
Gen1
Gen 1:
Genesis 1:-
Genesis 1:1
Genesis 1:1-2
Genesis 1:-3
Genesis 1-2
Genesis
Genesis 99
1 Cor 1
1cor1
1 cor 1:
1 cor 2:
1 cor 1:1-5
1 cor 2:3-1
jude 1
1 jude 1:
genesis1:1, genesis1
genesis1:1, genesis1,
genesis1:1,, genesis1,
gen1';,.fen fe efj
fpqm3]p 4 04 4jio4mngf
# a devilish Test
" select * from *;;;;;
walrus
and
lord
his
shall
they
even
therefore
should