-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
180 lines (150 loc) · 4.75 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import sqlite3
# from urllib.parse import urlencode
from functools import lru_cache
import uvicorn
from starlette.applications import Starlette
from starlette.exceptions import HTTPException
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Route, Mount
from starlette.staticfiles import StaticFiles
from starlette.middleware import Middleware
from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware
from starlette.middleware.cors import CORSMiddleware
query_str = """
SELECT
author,
year,
pages,
title,
place,
tags,
snippet(articles_fts, 6, '<b>', '</b>', '...', 60) text,
filename
FROM
articles_fts
WHERE
articles_fts = '' || ? || ''
and year is not NULL
ORDER BY :sort: :direction:
LIMIT cast(? as int) OFFSET cast(? as int)
"""
def get_connection() -> sqlite3.Connection:
# return sqlite3.connect("file:historisk-samfund.db?mode=ro", uri=True)
return sqlite3.connect("file:db.db?mode=ro", uri=True)
@lru_cache(maxsize=16)
def get_total_hits(q: str, year: str = None) -> int:
conn = get_connection()
where_clause = "WHERE articles_fts = ?"
if year:
where_clause += f" and year = {year}"
total: tuple = conn.execute(
f"SELECT COUNT(*) FROM articles_fts {where_clause}", (q,)
).fetchone()
return int(total[0])
def search_articles(request: Request):
conn = get_connection()
q: str = request.query_params["q"]
year: str = request.query_params.get("year")
sort: str = request.query_params.get("sort", "year")
if sort.lower() not in [
"title_desc",
"title_asc",
"year_desc",
"year_asc",
"author_asc",
"author_desc",
]:
sort = "year_asc"
direction: str = request.query_params.get("direction", "asc")
if direction.lower() not in ["asc", "desc"]:
direction = "asc"
size = int(request.query_params.get("size", 20))
offset = int(request.query_params.get("offset", 0))
total: int = get_total_hits(q, year)
# get result-rows
if year and 1908 <= int(year) <= 2014:
query_str2 = query_str.replace("year is not NULL", f"year = {year}")
prepared_stmt: str = query_str2.replace(":sort:", sort.split("_")[0]).replace(
":direction:", sort.split("_")[1]
)
else:
prepared_stmt: str = query_str.replace(":sort:", sort.split("_")[0]).replace(
":direction:", sort.split("_")[1]
)
rows: list[dict] = []
for row in conn.execute(
prepared_stmt,
(
q,
size,
offset,
),
):
rows.append(
{
"author": row[0],
"year": row[1],
"pages": row[2],
"title": row[3],
"place": row[4],
"tags": row[5],
"snippet": row[6],
"filename": row[7],
}
)
out = {
"q": q,
"size": size,
"sort": sort,
"offset": offset,
"rows": rows,
"total": total,
}
# if the optional year-filter is present, add it to output
if year:
out["year"] = int(year)
# hvis offset plus size er mindre en total, så kan vi gå videre
if offset + size < int(total):
if "offset" not in request.url.query:
out["next"] = f"{request.url.query}&offset={offset + size}"
else:
out["next"] = request.url.query.replace(
f"offset={offset}", f"offset={offset + size}"
)
# hvis vi er offset mere end size, så kan vi gå tilbage
if offset - size >= 0:
if "offset" not in request.url.query:
out["previous"] = f"{request.url.query}&offset={offset - size}"
else:
out["previous"] = request.url.query.replace(
f"offset={offset}", f"offset={offset - size}"
)
return JSONResponse(out)
async def http_exception(request: Request, exc: HTTPException):
return JSONResponse(
{"detail": exc.detail}, status_code=exc.status_code, headers=exc.headers
)
routes = [
Route("/search", endpoint=search_articles, methods=["GET"]),
Mount("/static", app=StaticFiles(directory="statics"), name="static"),
]
middleware = [
Middleware(HTTPSRedirectMiddleware),
Middleware(
CORSMiddleware, allow_origins=["*"], allow_methods=["GET", "HEAD", "OPTIONS"]
),
]
exception_handlers = {
HTTPException: http_exception
# 404: not_found,
# 500: server_error
}
app = Starlette(
routes=routes,
debug=True,
middleware=middleware,
exception_handlers=exception_handlers,
)
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)