cleanup
This commit is contained in:
@@ -7,8 +7,9 @@ import time
|
||||
import datetime
|
||||
import traceback
|
||||
import aiosqlite as sqlite3
|
||||
from typing import LiteralString, Optional
|
||||
from typing import LiteralString, Optional, Union
|
||||
from fastapi import FastAPI, Request, HTTPException
|
||||
from fastapi.responses import JSONResponse
|
||||
from .constructors import ValidTopKarmaRequest, ValidKarmaRetrievalRequest,\
|
||||
ValidKarmaUpdateRequest
|
||||
|
||||
@@ -18,12 +19,12 @@ class KarmaDB:
|
||||
self.db_path: LiteralString = os.path.join("/", "usr", "local", "share",
|
||||
"sqlite_dbs", "karma.db")
|
||||
|
||||
async def get_karma(self, keyword: str) -> int | dict:
|
||||
async def get_karma(self, keyword: str) -> Union[int, dict]:
|
||||
"""Get Karma Value for Keyword
|
||||
Args:
|
||||
keyword (str): The keyword to search
|
||||
Returns:
|
||||
int|dict
|
||||
Union[int, dict]
|
||||
"""
|
||||
async with sqlite3.connect(self.db_path, timeout=2) as db_conn:
|
||||
async with await db_conn.execute("SELECT score FROM karma WHERE keyword LIKE ? LIMIT 1", (keyword,)) as db_cursor:
|
||||
@@ -37,7 +38,8 @@ class KarmaDB:
|
||||
}
|
||||
|
||||
async def get_top(self, n: Optional[int] = 10) -> Optional[list[tuple]]:
|
||||
"""Get Top n=10 Karma Entries
|
||||
"""
|
||||
Get Top n=10 Karma Entries
|
||||
Args:
|
||||
n (Optional[int]) = 10: The number of top results to return
|
||||
Returns:
|
||||
@@ -51,8 +53,10 @@ class KarmaDB:
|
||||
traceback.print_exc()
|
||||
return None
|
||||
|
||||
async def update_karma(self, granter: str, keyword: str, flag: int) -> Optional[bool]:
|
||||
"""Update Karma for Keyword
|
||||
async def update_karma(self, granter: str, keyword: str,
|
||||
flag: int) -> Optional[bool]:
|
||||
"""
|
||||
Update Karma for Keyword
|
||||
Args:
|
||||
granter (str): The user who granted (increased/decreased) the karma
|
||||
keyword (str): The keyword to update
|
||||
@@ -93,9 +97,11 @@ class KarmaDB:
|
||||
return False
|
||||
|
||||
class Karma(FastAPI):
|
||||
"""Karma Endpoints"""
|
||||
def __init__(self, app: FastAPI, util, constants): # pylint: disable=super-init-not-called
|
||||
self.app = app
|
||||
"""
|
||||
Karma Endpoints
|
||||
"""
|
||||
def __init__(self, app: FastAPI, util, constants) -> None: # pylint: disable=super-init-not-called
|
||||
self.app: FastAPI = app
|
||||
self.util = util
|
||||
self.constants = constants
|
||||
self.db = KarmaDB()
|
||||
@@ -111,8 +117,11 @@ class Karma(FastAPI):
|
||||
include_in_schema=False)
|
||||
|
||||
|
||||
async def top_karma_handler(self, request: Request, data: ValidTopKarmaRequest | None = None) -> list[tuple]|dict:
|
||||
"""Get top keywords for karma"""
|
||||
async def top_karma_handler(self, request: Request,
|
||||
data: Optional[ValidTopKarmaRequest] = None) -> JSONResponse:
|
||||
"""
|
||||
Get top keywords for karma
|
||||
"""
|
||||
|
||||
if not self.util.check_key(request.url.path, request.headers.get('X-Authd-With')):
|
||||
raise HTTPException(status_code=403, detail="Unauthorized")
|
||||
@@ -125,19 +134,20 @@ class Karma(FastAPI):
|
||||
try:
|
||||
top10: Optional[list[tuple]] = await self.db.get_top(n=n)
|
||||
if not top10:
|
||||
return {
|
||||
return JSONResponse(status_code=500, content={
|
||||
'err': True,
|
||||
'errorText': 'General failure',
|
||||
}
|
||||
return top10
|
||||
})
|
||||
return JSONResponse(content=top10)
|
||||
except:
|
||||
traceback.print_exc()
|
||||
return {
|
||||
return JSONResponse(status_code=500, content={
|
||||
'err': True,
|
||||
'errorText': 'Exception occurred.',
|
||||
}
|
||||
})
|
||||
|
||||
async def get_karma_handler(self, data: ValidKarmaRetrievalRequest, request: Request):
|
||||
async def get_karma_handler(self, data: ValidKarmaRetrievalRequest,
|
||||
request: Request) -> JSONResponse:
|
||||
"""Get current karma value"""
|
||||
|
||||
if not self.util.check_key(request.url.path, request.headers.get('X-Authd-With')):
|
||||
@@ -145,30 +155,32 @@ class Karma(FastAPI):
|
||||
|
||||
keyword: str = data.keyword
|
||||
try:
|
||||
count: int|dict = await self.db.get_karma(keyword)
|
||||
return {
|
||||
count: Union[int, dict] = await self.db.get_karma(keyword)
|
||||
return JSONResponse(content={
|
||||
'keyword': keyword,
|
||||
'count': count,
|
||||
}
|
||||
})
|
||||
except:
|
||||
traceback.print_exc()
|
||||
return {
|
||||
return JSONResponse(status_code=500, content={
|
||||
'err': True,
|
||||
'errorText': "Exception occurred."
|
||||
}
|
||||
'errorText': "Exception occurred.",
|
||||
})
|
||||
|
||||
async def modify_karma_handler(self, data: ValidKarmaUpdateRequest, request: Request) -> dict:
|
||||
async def modify_karma_handler(self, data: ValidKarmaUpdateRequest,
|
||||
request: Request) -> JSONResponse:
|
||||
"""Update karma count"""
|
||||
|
||||
if not self.util.check_key(request.url.path, request.headers.get('X-Authd-With'), 2):
|
||||
raise HTTPException(status_code=403, detail="Unauthorized")
|
||||
|
||||
if not data.flag in [0, 1]:
|
||||
return {
|
||||
return JSONResponse(status_code=500, content={
|
||||
'err': True,
|
||||
'errorText': 'Invalid request'
|
||||
}
|
||||
'errorText': 'Invalid request',
|
||||
})
|
||||
|
||||
return {
|
||||
'success': await self.db.update_karma(data.granter, data.keyword, data.flag)
|
||||
}
|
||||
return JSONResponse(content={
|
||||
'success': await self.db.update_karma(data.granter,
|
||||
data.keyword, data.flag)
|
||||
})
|
||||
Reference in New Issue
Block a user