From 3ad75b6eb809ffad58c29d134f19635b1d7033c6 Mon Sep 17 00:00:00 2001 From: anima Date: Fri, 7 Mar 2025 15:56:31 +0100 Subject: [PATCH] add config file option --- .gitignore | 1 + PiholeAPI.py | 17 +++++++++++------ pihole.json.sample | 6 ++++++ 3 files changed, 18 insertions(+), 6 deletions(-) create mode 100644 pihole.json.sample diff --git a/.gitignore b/.gitignore index 658bfae..ec9e94d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ *.conf +*.json # ---> Python # Byte-compiled / optimized / DLL files diff --git a/PiholeAPI.py b/PiholeAPI.py index 2304836..745efab 100644 --- a/PiholeAPI.py +++ b/PiholeAPI.py @@ -13,6 +13,7 @@ import logging import requests import json from datetime import datetime, timedelta +from os import path # log settings @@ -20,14 +21,18 @@ logging.basicConfig(format='[%(asctime)s] %(levelname)s %(message)s', level=logg class PiholeAPI: - def __init__(self, url: str, port: int = 80, ssl: bool = False, passwd: str = None): - self.url = url + def __init__(self, config: str = 'pihole.json', host: str = None, port: int = 80, ssl: bool = False, password: str = None): + self.host = host self.port = port self.ssl = ssl - self.passwd = passwd + self.password = password self.valid_auth = datetime.now() self.sid = None self.csrf = None + if path.exists(config): + with open(config, 'r') as file: + for key, value in json.load(file).items(): + self.__dict__[key] = value def __query(self, query: str, method: str = 'GET', payload: dict = None, auth_need: bool = True): headers = dict() @@ -49,7 +54,7 @@ class PiholeAPI: url = 'http' if self.ssl: url += 's' - url += f'://{self.url}:{self.port}/api/{query}' + url += f'://{self.host}:{self.port}/api/{query}' if payload: response = requests.request(method=method, url=url, headers=headers, json=payload, verify=False) @@ -109,7 +114,7 @@ class PiholeAPI: Returns: bool: True if auth successfull """ - payload = {'password': self.passwd} + payload = {'password': self.password} data = self.__query('auth', 'POST', payload, auth_need=False) if not data: raise PermissionError(f'Authentication not possible') @@ -167,7 +172,7 @@ class PiholeAPI: def main(): - pi = PiholeAPI(url='localhost', passwd='my-password!') + pi = PiholeAPI() pi.get_sessions() diff --git a/pihole.json.sample b/pihole.json.sample new file mode 100644 index 0000000..472f149 --- /dev/null +++ b/pihole.json.sample @@ -0,0 +1,6 @@ +{ + "host": "localhost", + "port": 80, + "ssl": false, + "password": "mypassword" +} \ No newline at end of file