root: migrate from os.path to Pathlib (#5594)

Signed-off-by: Jens Langhammer <jens@goauthentik.io>
This commit is contained in:
Jens L 2023-05-12 20:04:02 +02:00 committed by GitHub
parent a032fd529b
commit 6299fc7f81
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 21 additions and 18 deletions

View file

@ -1,5 +1,5 @@
"""core Configs API""" """core Configs API"""
from os import path from pathlib import Path
from django.conf import settings from django.conf import settings
from django.db import models from django.db import models
@ -63,7 +63,7 @@ class ConfigView(APIView):
"""Get all capabilities this server instance supports""" """Get all capabilities this server instance supports"""
caps = [] caps = []
deb_test = settings.DEBUG or settings.TEST deb_test = settings.DEBUG or settings.TEST
if path.ismount(settings.MEDIA_ROOT) or deb_test: if Path(settings.MEDIA_ROOT).is_mount() or deb_test:
caps.append(Capabilities.CAN_SAVE_MEDIA) caps.append(Capabilities.CAN_SAVE_MEDIA)
if GEOIP_READER.enabled: if GEOIP_READER.enabled:
caps.append(Capabilities.CAN_GEO_IP) caps.append(Capabilities.CAN_GEO_IP)

View file

@ -5,6 +5,7 @@ from contextlib import contextmanager
from glob import glob from glob import glob
from json import dumps, loads from json import dumps, loads
from json.decoder import JSONDecodeError from json.decoder import JSONDecodeError
from pathlib import Path
from sys import argv, stderr from sys import argv, stderr
from time import time from time import time
from typing import Any from typing import Any
@ -42,22 +43,25 @@ class ConfigLoader:
def __init__(self): def __init__(self):
super().__init__() super().__init__()
self.__config = {} self.__config = {}
base_dir = os.path.realpath(os.path.join(os.path.dirname(__file__), "../..")) base_dir = Path(__file__).parent.joinpath(Path("../..")).resolve()
for path in SEARCH_PATHS: for _path in SEARCH_PATHS:
path = Path(_path)
# Check if path is relative, and if so join with base_dir # Check if path is relative, and if so join with base_dir
if not os.path.isabs(path): if not path.is_absolute():
path = os.path.join(base_dir, path) path = base_dir / path
if os.path.isfile(path) and os.path.exists(path): if path.is_file() and path.exists():
# Path is an existing file, so we just read it and update our config with it # Path is an existing file, so we just read it and update our config with it
self.update_from_file(path) self.update_from_file(path)
elif os.path.isdir(path) and os.path.exists(path): elif path.is_dir() and path.exists():
# Path is an existing dir, so we try to read the env config from it # Path is an existing dir, so we try to read the env config from it
env_paths = [ env_paths = [
os.path.join(path, ENVIRONMENT + ".yml"), path / Path(ENVIRONMENT + ".yml"),
os.path.join(path, ENVIRONMENT + ".env.yml"), path / Path(ENVIRONMENT + ".env.yml"),
path / Path(ENVIRONMENT + ".yaml"),
path / Path(ENVIRONMENT + ".env.yaml"),
] ]
for env_file in env_paths: for env_file in env_paths:
if os.path.isfile(env_file) and os.path.exists(env_file): if env_file.is_file() and env_file.exists():
# Update config with env file # Update config with env file
self.update_from_file(env_file) self.update_from_file(env_file)
self.update_from_env() self.update_from_env()
@ -99,13 +103,13 @@ class ConfigLoader:
value = url.query value = url.query
return value return value
def update_from_file(self, path: str): def update_from_file(self, path: Path):
"""Update config from file contents""" """Update config from file contents"""
try: try:
with open(path, encoding="utf8") as file: with open(path, encoding="utf8") as file:
try: try:
self.update(self.__config, yaml.safe_load(file)) self.update(self.__config, yaml.safe_load(file))
self.log("debug", "Loaded config", file=path) self.log("debug", "Loaded config", file=str(path))
self.loaded_file.append(path) self.loaded_file.append(path)
except yaml.YAMLError as exc: except yaml.YAMLError as exc:
raise ImproperlyConfigured from exc raise ImproperlyConfigured from exc

View file

@ -4,6 +4,7 @@ import importlib
import logging import logging
import os import os
from hashlib import sha512 from hashlib import sha512
from pathlib import Path
from urllib.parse import quote_plus from urllib.parse import quote_plus
import structlog import structlog
@ -19,11 +20,9 @@ from authentik.stages.password import BACKEND_APP_PASSWORD, BACKEND_INBUILT, BAC
LOGGER = structlog.get_logger() LOGGER = structlog.get_logger()
# Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = Path(__file__).absolute().parent.parent.parent
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) STATICFILES_DIRS = [BASE_DIR / Path("web")]
STATIC_ROOT = BASE_DIR + "/static" MEDIA_ROOT = BASE_DIR / Path("media")
STATICFILES_DIRS = [BASE_DIR + "/web"]
MEDIA_ROOT = BASE_DIR + "/media"
DEBUG = CONFIG.y_bool("debug") DEBUG = CONFIG.y_bool("debug")
SECRET_KEY = CONFIG.y("secret_key") SECRET_KEY = CONFIG.y("secret_key")