2023-09-02 21:30:20 -07:00
|
|
|
import functools
|
2023-09-09 01:46:40 -07:00
|
|
|
import random
|
2023-08-29 03:01:06 -07:00
|
|
|
import requests
|
|
|
|
import os
|
2023-09-02 21:30:20 -07:00
|
|
|
from flask import current_app, json
|
|
|
|
from app import db
|
|
|
|
from app.models import Settings
|
2023-08-29 03:01:06 -07:00
|
|
|
|
|
|
|
|
|
|
|
# ----------------------------------------------------------------------
|
|
|
|
# Jinja: when a file was modified. Useful for cache-busting
|
|
|
|
def getmtime(filename):
|
|
|
|
return os.path.getmtime('static/' + filename)
|
|
|
|
|
|
|
|
|
|
|
|
# do a GET request to a uri, return the result
|
|
|
|
def get_request(uri, params=None, headers=None) -> requests.Response:
|
|
|
|
try:
|
|
|
|
response = requests.get(uri, params=params, headers=headers, timeout=1, allow_redirects=True)
|
|
|
|
except requests.exceptions.SSLError as invalid_cert:
|
|
|
|
# Not our problem if the other end doesn't have proper SSL
|
|
|
|
current_app.logger.info(f"{uri} {invalid_cert}")
|
|
|
|
raise requests.exceptions.SSLError from invalid_cert
|
|
|
|
except ValueError as ex:
|
|
|
|
# Convert to a more generic error we handle
|
|
|
|
raise requests.exceptions.RequestException(f"InvalidCodepoint: {str(ex)}") from None
|
|
|
|
|
|
|
|
return response
|
2023-09-02 21:30:20 -07:00
|
|
|
|
|
|
|
|
2023-09-09 01:46:40 -07:00
|
|
|
# saves an arbitrary object into a persistent key-value store. Possibly redis would be faster than using the DB
|
2023-09-02 21:30:20 -07:00
|
|
|
@functools.lru_cache(maxsize=100)
|
|
|
|
def get_setting(name: str, default=None):
|
|
|
|
setting = Settings.query.filter_by(name=name).first()
|
|
|
|
if setting is None:
|
|
|
|
return default
|
|
|
|
else:
|
|
|
|
return json.loads(setting.value)
|
|
|
|
|
|
|
|
|
2023-09-09 01:46:40 -07:00
|
|
|
# retrieves arbitrary object from persistent key-value store
|
2023-09-02 21:30:20 -07:00
|
|
|
def set_setting(name: str, value):
|
|
|
|
setting = Settings.query.filter_by(name=name).first()
|
|
|
|
if setting is None:
|
|
|
|
db.session.append(Settings(name=name, value=json.dumps(value)))
|
|
|
|
else:
|
|
|
|
setting.value = json.dumps(value)
|
|
|
|
db.session.commit()
|
|
|
|
get_setting.cache_clear()
|
2023-09-05 01:25:10 -07:00
|
|
|
|
|
|
|
|
|
|
|
# Return the contents of a file as a string. Inspired by PHP's function of the same name.
|
|
|
|
def file_get_contents(filename):
|
|
|
|
with open(filename, 'r') as file:
|
|
|
|
contents = file.read()
|
|
|
|
return contents
|
2023-09-09 01:46:40 -07:00
|
|
|
|
|
|
|
|
|
|
|
random_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
|
|
|
|
|
|
|
|
|
|
|
def gibberish(length: int = 10) -> str:
|
|
|
|
return "".join([random.choice(random_chars) for x in range(length)])
|