import json import os import random import string from dataclasses import dataclass from datetime import datetime from pathlib import Path from urllib.parse import urlunparse from loguru import logger @dataclass class BaseUrl: """utility class to create a url string with urllib""" netloc: str scheme: str = "https" path: str = "" params: str = "" query: str = "" fragment: str = "" def get(self, path: str = ""): return urlunparse((self.scheme, self.netloc, path, self.params, self.query, self.fragment)) def get_datetime_string() -> str: current_datetime = datetime.now() return current_datetime.strftime("%Y-%m-%d-%H-%M-%S") def rmtree(root_dir: Path) -> None: """removes a folder with content recursively""" if not root_dir.is_dir(): return for child in root_dir.iterdir(): if child.is_dir(): rmtree(child) else: child.unlink() root_dir.rmdir() def generate_random_string(length: int, punctuation=False) -> str: """returns a random string of the given length""" characters = string.ascii_letters + string.digits if punctuation: characters += string.punctuation random_string = "".join(random.choice(characters) for _ in range(length)) return random_string def load_json_to_environ(cred_file: Path) -> None: """Load the contents of a json file directly into os.environ. Variable names are inherited""" if not cred_file.is_file(): logger.warning(f"{cred_file} could not be found, no credentials loaded") return with open(cred_file, "r") as f: CREDENTIALS = json.load(f) for key, value in CREDENTIALS.items(): os.environ[key] = value