From 1cf0531b309059290885ef38bdafd94929a5e097 Mon Sep 17 00:00:00 2001 From: bad Date: Sat, 4 Jun 2022 22:18:32 +0200 Subject: [PATCH] Initial commit --- .gitignore | 163 ++++++++++++++++++++++++++++++++++++++++++ app.py | 35 +++++++++ flake.lock | 42 +++++++++++ flake.nix | 31 ++++++++ mypy.ini | 29 ++++++++ plugin.py | 56 +++++++++++++++ plugins/__init__.py | 0 plugins/log_plugin.py | 21 ++++++ pronoun_update.py | 8 +++ setup.py | 14 ++++ test_plugin.py | 13 ++++ 11 files changed, 412 insertions(+) create mode 100644 .gitignore create mode 100644 app.py create mode 100644 flake.lock create mode 100644 flake.nix create mode 100644 mypy.ini create mode 100644 plugin.py create mode 100644 plugins/__init__.py create mode 100644 plugins/log_plugin.py create mode 100644 pronoun_update.py create mode 100644 setup.py create mode 100644 test_plugin.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6900d43 --- /dev/null +++ b/.gitignore @@ -0,0 +1,163 @@ +# nix +result +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + diff --git a/app.py b/app.py new file mode 100644 index 0000000..2597115 --- /dev/null +++ b/app.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python + +from plugin import Plugin, load_plugins_for_config +from typing import Tuple +from flask import Flask, request +from pronoun_update import PronounUpdate + +import asyncio + +app = Flask(__name__) + +plugins = load_plugins_for_config(app.config.get("PLUGINS", [{"name": "log"}])) + + +async def trigger_update_pronouns(pronouns: str) -> None: + update = PronounUpdate(pronouns) + await asyncio.gather(*[plugin.update_bio(update) for plugin in plugins]) + + +@app.route("/update_pronouns", methods=["POST"]) +async def update_pronouns() -> Tuple[str, int]: + pronouns = request.values.get("pronouns") + if not pronouns: + return "Please specify a pronouns parameter as a part of your request", 422 + + await trigger_update_pronouns(pronouns) + return pronouns, 200 + + +if __name__ == "__main__": + import logging + + logging.getLogger().setLevel("INFO") + + app.run(host="0.0.0.0", port=8080) diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..56c763f --- /dev/null +++ b/flake.lock @@ -0,0 +1,42 @@ +{ + "nodes": { + "flake-utils": { + "locked": { + "lastModified": 1653893745, + "narHash": "sha256-0jntwV3Z8//YwuOjzhV2sgJJPt+HY6KhU7VZUL0fKZQ=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "1ed9fb1935d260de5fe1c2f7ee0ebaae17ed2fa1", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1654201634, + "narHash": "sha256-iR4gse4ULU1psZiKCQ8TC+LmIAjfZ79hGwtgogmgPmI=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "17e891b141ca8e599ebf6443d0870a67dd98f94f", + "type": "github" + }, + "original": { + "owner": "NixOS", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "flake-utils": "flake-utils", + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..5e8a063 --- /dev/null +++ b/flake.nix @@ -0,0 +1,31 @@ +{ + description = "A very basic flake"; + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs"; + flake-utils = { + url = "github:numtide/flake-utils"; + inputs.nixpkgs.follows = "nixpkgs"; + }; + }; + + outputs = { self, nixpkgs, flake-utils }: + flake-utils.lib.eachDefaultSystem (system: + let + pkgs = import nixpkgs { inherit system; }; + pythonPackages = pkgs.python310Packages; + pythonDeps = with pythonPackages; [ mypy flask pytest pylint black types-setuptools ]; + + in + { + packages.pronoun-o-matic = pythonPackages.buildPythonApplication { + pname = "pronoun-o-matic"; + version = "1.0"; + propagatedBuildInputs = pythonDeps; + src = ./.; + }; + devShell = pkgs.mkShell { + buildInputs = [pythonPackages.python] ++ pythonDeps; + }; + defaultPackage = self.packages.${system}.pronoun-o-matic; + }); +} diff --git a/mypy.ini b/mypy.ini new file mode 100644 index 0000000..535ba0a --- /dev/null +++ b/mypy.ini @@ -0,0 +1,29 @@ +[mypy] +exclude = result +python_version = 3.10 + +; Ensure full coverage +disallow_untyped_calls = True +disallow_untyped_defs = True +disallow_incomplete_defs = True +disallow_untyped_decorators = True +check_untyped_defs = True + +; Restrict dynamic typing +disallow_any_generics = True +disallow_subclassing_any = True +warn_return_any = True + +; Know exactly what you're doing +warn_redundant_casts = True +warn_unused_ignores = True +warn_unused_configs = True +warn_unreachable = True +show_error_codes = True + +; Explicit is better than implicit +no_implicit_optional = True + +[mypy-*.tests.*] +; pytest decorators are not typed +disallow_untyped_decorators = False diff --git a/plugin.py b/plugin.py new file mode 100644 index 0000000..b8adc35 --- /dev/null +++ b/plugin.py @@ -0,0 +1,56 @@ +from abc import abstractclassmethod, abstractmethod +from pronoun_update import PronounUpdate +from typing import Any, Callable, List +from importlib.metadata import entry_points +from functools import cache + + +class Plugin: + @classmethod + @abstractmethod + def name(cls) -> str: + pass + + @abstractmethod + def __init__(self, config: dict[str, str]): + pass + + @abstractmethod + async def update_bio(self, update_pronouns: PronounUpdate) -> None: + pass + + +@cache +def load_plugins() -> dict[str, type[Plugin]]: + plugins: dict[str, type[Plugin]] = {} + # Ignore the following two lines due to incorrect type definition for entry_points + # See: https://github.com/python/typeshed/pull/7331 + for plugin in entry_points(group="pronounomatic.plugins"): # type: ignore + pl = plugin.load() # type: ignore + assert issubclass(pl, Plugin) + plugins[pl.name()] = pl + + return plugins + + +class InvalidPluginDefinitionException(Exception): + pass + + +def load_plugins_for_config(config: list[dict[str, Any]]) -> List[Plugin]: + plugins = [] + plugin_classes = load_plugins() + for plugin_def in config: + if not plugin_def["name"]: + raise InvalidPluginDefinitionException("Missing plugin_name field") + plugin_name = plugin_def["name"] + if not plugin_name in load_plugins(): + raise InvalidPluginDefinitionException( + f"No plugin with name {plugin_name} loaded" + ) + + plugin_cls = plugin_classes[plugin_name] + plugin = plugin_cls(plugin_def) + plugins.append(plugin) + + return plugins diff --git a/plugins/__init__.py b/plugins/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/log_plugin.py b/plugins/log_plugin.py new file mode 100644 index 0000000..e886f66 --- /dev/null +++ b/plugins/log_plugin.py @@ -0,0 +1,21 @@ +import logging +from pronoun_update import PronounUpdate +from typing import Any +from plugin import Plugin + + +class LogPlugin(Plugin): + log_level: int + + @classmethod + def name(cls) -> str: + return "log" + + def __init__(self, config: dict[str, Any]): + log_level_str = config.get("level", "INFO") + self.log_level = logging.getLevelName(log_level_str) + + """ A simple plugin that simply logs the pronoun update """ + + async def update_bio(self, pronoun_update: PronounUpdate) -> None: + logging.log(self.log_level, f"Updating pronouns to: {pronoun_update.pronouns}") diff --git a/pronoun_update.py b/pronoun_update.py new file mode 100644 index 0000000..a20cc7e --- /dev/null +++ b/pronoun_update.py @@ -0,0 +1,8 @@ +class PronounUpdate: + pronouns: str + + def __init__(self, pronouns: str): + self.pronouns = pronouns + + def replace_pronouns_in_bio(self, bio: str) -> str: + return self.pronouns diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..772d17f --- /dev/null +++ b/setup.py @@ -0,0 +1,14 @@ +#!/usr/bin/env python + +from setuptools import setup, find_packages + +setup( + name="pronoun-o-matic", + version="1.0", + # Modules to import from other scripts: + packages=find_packages(), + package_dir={"": "./"}, + entry_points={"pronounomatic.plugins": "test = plugins.log_plugin:LogPlugin"}, + # Executables + scripts=["app.py"], +) diff --git a/test_plugin.py b/test_plugin.py new file mode 100644 index 0000000..d6a1424 --- /dev/null +++ b/test_plugin.py @@ -0,0 +1,13 @@ +import logging +from plugins.log_plugin import LogPlugin +from plugin import load_plugins_for_config + + +def test_load_plugins_for_config() -> None: + config = [{"name": "log", "level": "DEBUG"}] + + plugins = load_plugins_for_config(config) + # The only plugin loaded should be the log plugin + log_plugin = plugins[0] + assert isinstance(log_plugin, LogPlugin) + assert log_plugin.log_level == logging.getLevelName("DEBUG")