PhotosAPI/modules/utils.py

88 lines
2.4 KiB
Python
Raw Permalink Normal View History

2023-06-23 12:25:27 +03:00
import logging
2023-06-23 12:17:02 +03:00
from pathlib import Path
2023-06-23 12:25:27 +03:00
from traceback import format_exc
2023-06-22 14:17:53 +03:00
from typing import Any, Union
from ujson import JSONDecodeError, dumps, loads
2022-12-20 02:22:32 +02:00
2023-06-23 12:25:27 +03:00
logger = logging.getLogger(__name__)
2022-12-20 02:22:32 +02:00
2023-03-12 15:59:13 +02:00
2023-06-23 12:17:02 +03:00
def jsonLoad(filepath: Union[str, Path]) -> Any:
2022-12-20 02:22:32 +02:00
"""Load json file
### Args:
2023-06-23 12:17:02 +03:00
* filepath (`Union[str, Path]`): Path to input file
2022-12-20 02:22:32 +02:00
### Returns:
* `Any`: Some json deserializable
2023-03-12 15:59:13 +02:00
"""
with open(filepath, "r", encoding="utf8") as file:
2022-12-20 02:22:32 +02:00
try:
output = loads(file.read())
except JSONDecodeError:
2023-06-23 12:25:27 +03:00
logger.error(
"Could not load json file %s: file seems to be incorrect!\n%s",
filepath,
format_exc(),
2023-03-12 15:59:13 +02:00
)
2022-12-20 02:22:32 +02:00
raise
except FileNotFoundError:
2023-06-23 12:25:27 +03:00
logger.error(
"Could not load json file %s: file does not seem to exist!\n%s",
filepath,
format_exc(),
2023-03-12 15:59:13 +02:00
)
2022-12-20 02:22:32 +02:00
raise
file.close()
return output
2023-03-12 15:59:13 +02:00
2023-06-23 12:17:02 +03:00
def jsonSave(contents: Union[list, dict], filepath: Union[str, Path]) -> None:
2022-12-20 02:22:32 +02:00
"""Save contents into json file
### Args:
* contents (`Union[list, dict]`): Some json serializable
2023-06-23 12:17:02 +03:00
* filepath (`Union[str, Path]`): Path to output file
2023-03-12 15:59:13 +02:00
"""
2022-12-20 02:22:32 +02:00
try:
2023-03-12 15:59:13 +02:00
with open(filepath, "w", encoding="utf8") as file:
2022-12-20 02:22:32 +02:00
file.write(dumps(contents, ensure_ascii=False, indent=4))
file.close()
2023-08-14 14:44:07 +03:00
except Exception as exc:
logger.error("Could not save json file %s: %s\n%s", filepath, exc, format_exc())
2022-12-20 02:22:32 +02:00
return
2023-03-12 15:59:13 +02:00
2022-12-20 02:22:32 +02:00
def configGet(key: str, *args: str) -> Any:
"""Get value of the config key
### Args:
* key (`str`): The last key of the keys path.
* *args (`str`): Path to key like: dict[args][key].
### Returns:
* `Any`: Value of provided key
2023-03-12 15:59:13 +02:00
"""
2023-06-23 12:17:02 +03:00
this_dict = jsonLoad(Path("config.json"))
2022-12-20 02:22:32 +02:00
this_key = this_dict
for dict_key in args:
this_key = this_key[dict_key]
return this_key[key]
2023-03-12 15:59:13 +02:00
2022-12-20 02:22:32 +02:00
def apiKeyInvalid(obj):
obj.send_response(401)
2023-03-12 15:59:13 +02:00
obj.send_header("Content-type", "application/json; charset=utf-8")
2022-12-20 02:22:32 +02:00
obj.end_headers()
obj.wfile.write(b'{"code":401, "message": "Invalid API key"}')
return
2023-03-12 15:59:13 +02:00
2022-12-20 02:22:32 +02:00
def apiKeyExpired(obj):
obj.send_response(403)
2023-03-12 15:59:13 +02:00
obj.send_header("Content-type", "application/json; charset=utf-8")
2022-12-20 02:22:32 +02:00
obj.end_headers()
obj.wfile.write(b'{"code":403, "message": "API key expired"}')
2023-03-12 15:59:13 +02:00
return