Source code for flux_restful.library.helpers

import json
import os.path
import re

import markdown
from fastapi import HTTPException

# Pages are simple names, so no path separators or dots
PAGE_NAME = re.compile(r"^[A-Za-z0-9_-]+\.md$")


[docs]def has_boolean_arg(payload, key): """ A helper to determine if a payload has a key, and it's in some derivation of True """ return key in payload and payload.get(key) in [True, "true"]
[docs]def get_int_arg(payload, key): """ Attempt to get (and parse) and integer argument. Fallback to None. """ arg = payload.get(key) if arg: try: arg = int(arg) except ValueError: arg = None return arg
[docs]def read_json(filename): with open(filename, "r") as fd: content = json.loads(fd.read()) return content
[docs]def get_page(name): """ Get a <page>.md file from the app root. """ package_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if not PAGE_NAME.match(name): raise HTTPException(status_code=404, detail="Page not found") filepath = os.path.join(package_dir, "pages", name) if not os.path.isfile(filepath): raise HTTPException(status_code=404, detail="Page not found") with open(filepath, "r", encoding="utf-8") as input_file: text = input_file.read() html = markdown.markdown(text) data = {"text": html} return data