diff options
| -rw-r--r-- | .gitignore | 2 | ||||
| -rw-r--r-- | kerbana/__init__.py | 80 | ||||
| -rw-r--r-- | kerbana/asgi.py | 16 | ||||
| -rw-r--r-- | kerbana/config.py | 20 | ||||
| -rw-r--r-- | kerbana/mqtt.py | 47 | ||||
| -rw-r--r-- | kerbana/settings.py | 125 | ||||
| -rw-r--r-- | kerbana/urls.py | 22 | ||||
| -rw-r--r-- | kerbana/wsgi.py | 16 | ||||
| -rwxr-xr-x | manage.py | 22 | ||||
| -rw-r--r-- | rrd/__init__.py | 0 | ||||
| -rw-r--r-- | rrd/admin.py | 3 | ||||
| -rw-r--r-- | rrd/apps.py | 6 | ||||
| -rw-r--r-- | rrd/migrations/__init__.py | 0 | ||||
| -rw-r--r-- | rrd/models.py | 3 | ||||
| -rw-r--r-- | rrd/tests.py | 3 | ||||
| -rw-r--r-- | rrd/urls.py | 7 | ||||
| -rw-r--r-- | rrd/views.py | 7 | ||||
| -rw-r--r-- | tests/test_app.py | 27 | ||||
| -rw-r--r-- | tests/test_mqtt.py | 32 | ||||
| -rw-r--r-- | unittest.cfg | 2 | 
20 files changed, 232 insertions, 208 deletions
@@ -1,6 +1,8 @@  *.pyc  .coverage +db.sqlite3 +  kerbana.toml  kerbana_tests.toml diff --git a/kerbana/__init__.py b/kerbana/__init__.py index cef433f..e69de29 100644 --- a/kerbana/__init__.py +++ b/kerbana/__init__.py @@ -1,80 +0,0 @@ -import os -from typing import Optional - -import flask -import toml - -from . import config, mqtt - - -def create_app(test_config: Optional[config.Config] = None): -    app = flask.Flask(__name__, instance_relative_config=True) - -    app.config.from_object(config.DefaultConfig) - -    if test_config is None: -        try: -            app.config.from_file( -                "/etc/kerbana/kerbana.toml", -                load=toml.load, -            ) -        except FileNotFoundError: -            app.logger.debug("File /etc/kerbana/kerbana.toml not found.") -        else: -            app.logger.debug( -                "Loaded configuration from /etc/kerbana/kerbana.toml" -            ) - -        try: -            app.config.from_file( -                os.path.join( -                    os.path.dirname(os.path.abspath(__file__)), -                    "..", -                    "kerbana.toml", -                ), -                load=toml.load, -            ) -        except FileNotFoundError: -            app.logger.debug("File kerbana.toml not found.") -        else: -            app.logger.debug("Loaded configuration from kerbana.toml") - -        try: -            app.config.from_envvar("KERBANA_CONFIG") -        except RuntimeError as e: -            app.logger.debug(e) -        except FileNotFoundError: -            app.logger.debug( -                "File {} (as found in $KERBANA_CONFIG) not found.".format( -                    os.environ["KERBANA_CONFIG"] -                ) -            ) -        else: -            app.logger.debug("Loaded configuration from $KERBANA_CONFIG") - -        app.config.from_prefixed_env(prefix="KERBANA_") -    else: -        app.config.from_object(test_config) -        try: -            app.config.from_file( -                os.path.join( -                    os.path.dirname(os.path.abspath(__file__)), -                    "..", -                    "kerbana_tests.toml", -                ), -                load=toml.load, -            ) -        except FileNotFoundError: -            app.logger.debug("File kerbana_tests.toml not found.") - -    mqtt_client = mqtt.MQTTClient(app) - -    if test_config is None: -        # If we're running tests, do not start the MQTTClient -        mqtt_client.connect() - -    @app.route('/') -    def root(): -        return "Hello World!" - -    return app diff --git a/kerbana/asgi.py b/kerbana/asgi.py new file mode 100644 index 0000000..7b864a5 --- /dev/null +++ b/kerbana/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for kerbana project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'kerbana.settings') + +application = get_asgi_application() diff --git a/kerbana/config.py b/kerbana/config.py deleted file mode 100644 index 93b0e54..0000000 --- a/kerbana/config.py +++ /dev/null @@ -1,20 +0,0 @@ -# Default configuration values - -class Config: -    SECRET_KEY = "dev" - -    MQTT_SERVER = "test.mosquitto.org" -    MQTT_PORT = 1883 -    MQTT_USER = None -    MQTT_PASSWORD = None -    MQTT_TOPIC = "kerbana/#" - - -class DefaultConfig(Config): -    pass - - -class TestConfig(Config): -    TESTING = True - -    MQTT_SERVER = "mqtt.invalid.org" diff --git a/kerbana/mqtt.py b/kerbana/mqtt.py deleted file mode 100644 index 3177287..0000000 --- a/kerbana/mqtt.py +++ /dev/null @@ -1,47 +0,0 @@ -import paho.mqtt.client as mqtt -from flask import Flask - - -class MQTTClient: -    def __init__(self, app: Flask): -        self.app = app -        self.reconnect = True -        self.connected = False - -        self.client = mqtt.Client() -        self.client.on_connect = self.on_connect -        self.client.on_disconnect = self.on_disconnect -        self.client.on_message = self.on_message - -    def connect(self): -        try: -            self.client.connect( -                self.app.config["MQTT_SERVER"], -                self.app.config["MQTT_PORT"], -                60,  # TODO: make the keepalive configurable -            ) -        except OSError as e: -            self.app.logger.warning("Could not connect to MQTT server") -            self.app.logger.warning(e) -        self.client.loop_start() - -    def disconnect(self, reconnect: bool = True): -        self.reconnect = reconnect -        self.client.loop_stop() -        self.client.disconnect() - -    def on_connect(self, client, userdata, flags, rc): -        self.app.logger.info("Connected to MQTT") -        self.connected = True -        client.subscribe(self.app.config["MQTT_TOPIC"]) - -    def on_disconnect(self, client, userdata, rc): -        self.app.logger.info("Disconnected from MQTT") -        self.connected = False -        if self.reconnect: -            self.connect() - -    def on_message(self, client, userdata, msg): -        self.app.logger.debug( -            "Received msg %s %s", msg.topic, msg.payload.decode() -        ) diff --git a/kerbana/settings.py b/kerbana/settings.py new file mode 100644 index 0000000..7be9578 --- /dev/null +++ b/kerbana/settings.py @@ -0,0 +1,125 @@ +""" +Django settings for kerbana project. + +Generated by 'django-admin startproject' using Django 3.2.21. + +For more information on this file, see +https://docs.djangoproject.com/en/3.2/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/3.2/ref/settings/ +""" + +from pathlib import Path + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'django-insecure-kvy1kjt(lsl7dqlm*zjwu9hd&j(g)pch0hec5tlbp2pvm_m5i=' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = [] + + +# Application definition + +INSTALLED_APPS = [ +    'django.contrib.admin', +    'django.contrib.auth', +    'django.contrib.contenttypes', +    'django.contrib.sessions', +    'django.contrib.messages', +    'django.contrib.staticfiles', +] + +MIDDLEWARE = [ +    'django.middleware.security.SecurityMiddleware', +    'django.contrib.sessions.middleware.SessionMiddleware', +    'django.middleware.common.CommonMiddleware', +    'django.middleware.csrf.CsrfViewMiddleware', +    'django.contrib.auth.middleware.AuthenticationMiddleware', +    'django.contrib.messages.middleware.MessageMiddleware', +    'django.middleware.clickjacking.XFrameOptionsMiddleware', +] + +ROOT_URLCONF = 'kerbana.urls' + +TEMPLATES = [ +    { +        'BACKEND': 'django.template.backends.django.DjangoTemplates', +        'DIRS': [], +        'APP_DIRS': True, +        'OPTIONS': { +            'context_processors': [ +                'django.template.context_processors.debug', +                'django.template.context_processors.request', +                'django.contrib.auth.context_processors.auth', +                'django.contrib.messages.context_processors.messages', +            ], +        }, +    }, +] + +WSGI_APPLICATION = 'kerbana.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/3.2/ref/settings/#databases + +DATABASES = { +    'default': { +        'ENGINE': 'django.db.backends.sqlite3', +        'NAME': BASE_DIR / 'db.sqlite3', +    } +} + + +# Password validation +# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ +    { +        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', +    }, +    { +        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', +    }, +    { +        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', +    }, +    { +        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', +    }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/3.2/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/3.2/howto/static-files/ + +STATIC_URL = '/static/' + +# Default primary key field type +# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' diff --git a/kerbana/urls.py b/kerbana/urls.py new file mode 100644 index 0000000..e8b7dd5 --- /dev/null +++ b/kerbana/urls.py @@ -0,0 +1,22 @@ +"""kerbana URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: +    https://docs.djangoproject.com/en/3.2/topics/http/urls/ +Examples: +Function views +    1. Add an import:  from my_app import views +    2. Add a URL to urlpatterns:  path('', views.home, name='home') +Class-based views +    1. Add an import:  from other_app.views import Home +    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home') +Including another URLconf +    1. Import the include() function: from django.urls import include, path +    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls')) +""" +from django.contrib import admin +from django.urls import include, path + +urlpatterns = [ +    path('rrd', include("rrd.urls")), +    path('admin/', admin.site.urls), +] diff --git a/kerbana/wsgi.py b/kerbana/wsgi.py new file mode 100644 index 0000000..b6cb550 --- /dev/null +++ b/kerbana/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for kerbana project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'kerbana.settings') + +application = get_wsgi_application() diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..96e4117 --- /dev/null +++ b/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): +    """Run administrative tasks.""" +    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'kerbana.settings') +    try: +        from django.core.management import execute_from_command_line +    except ImportError as exc: +        raise ImportError( +            "Couldn't import Django. Are you sure it's installed and " +            "available on your PYTHONPATH environment variable? Did you " +            "forget to activate a virtual environment?" +        ) from exc +    execute_from_command_line(sys.argv) + + +if __name__ == '__main__': +    main() diff --git a/rrd/__init__.py b/rrd/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/rrd/__init__.py diff --git a/rrd/admin.py b/rrd/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/rrd/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/rrd/apps.py b/rrd/apps.py new file mode 100644 index 0000000..ef97edc --- /dev/null +++ b/rrd/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class RrdConfig(AppConfig): +    default_auto_field = 'django.db.models.BigAutoField' +    name = 'rrd' diff --git a/rrd/migrations/__init__.py b/rrd/migrations/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/rrd/migrations/__init__.py diff --git a/rrd/models.py b/rrd/models.py new file mode 100644 index 0000000..71a8362 --- /dev/null +++ b/rrd/models.py @@ -0,0 +1,3 @@ +from django.db import models + +# Create your models here. diff --git a/rrd/tests.py b/rrd/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/rrd/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/rrd/urls.py b/rrd/urls.py new file mode 100644 index 0000000..5119061 --- /dev/null +++ b/rrd/urls.py @@ -0,0 +1,7 @@ +from django.urls import path + +from . import views + +urlpatterns = [ +    path("", views.index, name="index"), +] diff --git a/rrd/views.py b/rrd/views.py new file mode 100644 index 0000000..5357b77 --- /dev/null +++ b/rrd/views.py @@ -0,0 +1,7 @@ +import django.http +from django.shortcuts import render + +# Create your views here. + +def index(request): +    return django.http.HttpResponse("Hello, World") diff --git a/tests/test_app.py b/tests/test_app.py deleted file mode 100644 index 6cf29c5..0000000 --- a/tests/test_app.py +++ /dev/null @@ -1,27 +0,0 @@ -import os -import unittest -import unittest.mock - -from kerbana import config, create_app - - -class TestBase(unittest.TestCase): -    def setUp(self): -        test_config = config.TestConfig() -        self.app = create_app(test_config) -        self.client = self.app.test_client() - -    def test_root(self): -        res = self.client.get("/") -        self.assertEqual("Hello World!", res.data.decode()) - - -class TestConfig(unittest.TestCase): -    def test_default_config(self): -        app = create_app() -        self.assertEqual(app.config["SECRET_KEY"], "dev") - -    @unittest.mock.patch.dict(os.environ, {"KERBANA_CONFIG": "no_such_file"}) -    def test_kerbana_config_env_non_existing(self): -        app = create_app() -        self.assertEqual(app.config["SECRET_KEY"], "dev") diff --git a/tests/test_mqtt.py b/tests/test_mqtt.py deleted file mode 100644 index 20c1cf2..0000000 --- a/tests/test_mqtt.py +++ /dev/null @@ -1,32 +0,0 @@ -import time -import unittest - -from kerbana import config, create_app, mqtt - - -class TestMQTT(unittest.TestCase): -    def setUp(self): -        test_config = config.TestConfig() -        self.app = create_app(test_config) -        self.mqtt = mqtt.MQTTClient(self.app) -        self.mqtt.connect() -        time.sleep(0.1) -        if not self.mqtt.connected: -            self.skipTest("Could not find an mqtt server") - -    def tearDown(self): -        self.mqtt.disconnect(reconnect=False) - -    def test_disconnect(self): -        # after disconnecting from the mqtt server, we should -        # automatically reconnect -        self.mqtt.disconnect() -        time.sleep(2) -        self.assertTrue(self.mqtt.connected) - -    def test_disconnect_and_stay(self): -        # unless we really want to force a disconnection -        self.mqtt.disconnect(reconnect=False) -        time.sleep(2) -        self.assertFalse(self.mqtt.connected) -        self.assertFalse(self.mqtt.reconnect) diff --git a/unittest.cfg b/unittest.cfg deleted file mode 100644 index 7b30780..0000000 --- a/unittest.cfg +++ /dev/null @@ -1,2 +0,0 @@ -[log-capture] -clear-handlers = True  | 
