add config file option

This commit is contained in:
2025-03-07 15:56:31 +01:00
parent 34960aa608
commit 3ad75b6eb8
3 changed files with 18 additions and 6 deletions

1
.gitignore vendored
View File

@@ -1,4 +1,5 @@
*.conf *.conf
*.json
# ---> Python # ---> Python
# Byte-compiled / optimized / DLL files # Byte-compiled / optimized / DLL files

View File

@@ -13,6 +13,7 @@ import logging
import requests import requests
import json import json
from datetime import datetime, timedelta from datetime import datetime, timedelta
from os import path
# log settings # log settings
@@ -20,14 +21,18 @@ logging.basicConfig(format='[%(asctime)s] %(levelname)s %(message)s', level=logg
class PiholeAPI: class PiholeAPI:
def __init__(self, url: str, port: int = 80, ssl: bool = False, passwd: str = None): def __init__(self, config: str = 'pihole.json', host: str = None, port: int = 80, ssl: bool = False, password: str = None):
self.url = url self.host = host
self.port = port self.port = port
self.ssl = ssl self.ssl = ssl
self.passwd = passwd self.password = password
self.valid_auth = datetime.now() self.valid_auth = datetime.now()
self.sid = None self.sid = None
self.csrf = 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): def __query(self, query: str, method: str = 'GET', payload: dict = None, auth_need: bool = True):
headers = dict() headers = dict()
@@ -49,7 +54,7 @@ class PiholeAPI:
url = 'http' url = 'http'
if self.ssl: if self.ssl:
url += 's' url += 's'
url += f'://{self.url}:{self.port}/api/{query}' url += f'://{self.host}:{self.port}/api/{query}'
if payload: if payload:
response = requests.request(method=method, url=url, headers=headers, json=payload, verify=False) response = requests.request(method=method, url=url, headers=headers, json=payload, verify=False)
@@ -109,7 +114,7 @@ class PiholeAPI:
Returns: Returns:
bool: True if auth successfull bool: True if auth successfull
""" """
payload = {'password': self.passwd} payload = {'password': self.password}
data = self.__query('auth', 'POST', payload, auth_need=False) data = self.__query('auth', 'POST', payload, auth_need=False)
if not data: if not data:
raise PermissionError(f'Authentication not possible') raise PermissionError(f'Authentication not possible')
@@ -167,7 +172,7 @@ class PiholeAPI:
def main(): def main():
pi = PiholeAPI(url='localhost', passwd='my-password!') pi = PiholeAPI()
pi.get_sessions() pi.get_sessions()

6
pihole.json.sample Normal file
View File

@@ -0,0 +1,6 @@
{
"host": "localhost",
"port": 80,
"ssl": false,
"password": "mypassword"
}