Added autoload black magic, added decode flag to socket client

This commit is contained in:
aewens 2019-06-06 15:17:59 -04:00
parent 02af7e58a3
commit 20ff476e24
3 changed files with 24 additions and 5 deletions

View File

@ -5,4 +5,4 @@ from abots.helpers.general import eprint, deduce, noop, cast, get_digit, obtain
from abots.helpers.general import utc_now, utc_now_timestamp
from abots.helpers.logging import Logger
from abots.helpers.black_magic import infinitedict, debugger, singleton, curry
from abots.helpers.black_magic import coroutine, generator
from abots.helpers.black_magic import coroutine, generator, autoload

View File

@ -1,5 +1,7 @@
from collections import defaultdict
from functools import wraps
from os.path import dirname, basename, isfile, join
from glob import glob
from importlib import import_module
def infinitedict():
@ -57,4 +59,20 @@ def curry(func, argc=None):
return curry(curried, argc - len(args))
return wrapper_curry
# This is used to automatically import the files in this directory
# Essentially, it is a auto-loader for a plugin system
# NOTE: Do as I say, not as I do. You should probably never do this
def autoload(location, context, package, prefix=""):
level = -(len(package.split(".")) + 1)
for module in glob(join(dirname(location), "*.py")):
if not isfile(module) or module.endswith("__init__.py"):
continue
# Equivalent of doing "import <package>.<module>"
plugin = import_module(f".{basename(module)[:level]}", package)
funcs = [f for f in dir(plugin) if f[0] != "_"]
for func in funcs:
# Translates the above to "from <package>.<module> import *"
plugin_func = getattr(plugin, func)
# To reduce conflicts in global, the prefix is used here
# These should not be used directly and just fire off decorators
context[f"{prefix}{func}"] = plugin_func

View File

@ -20,7 +20,7 @@ from random import randint
class SocketClient(Thread):
def __init__(self, host, port, buffer_size=4096, secure=False,
timeout=None, daemon=False, reconnects=10):
timeout=None, daemon=False, reconnects=10, decode=True):
super().__init__()
self.setDaemon(daemon)
@ -30,6 +30,7 @@ class SocketClient(Thread):
self.secure = secure
self.timeout = timeout
self.reconnects = reconnects
self.decode = decode
self.sock = socket(AF_INET, SOCK_STREAM)
if self.secure:
self.sock = wrap_socket(self.sock)
@ -90,10 +91,10 @@ class SocketClient(Thread):
self.reconnecting.wait()
self.send_message(message)
def _get_message(self, decode=True):
def _get_message(self):
try:
packet = self.sock.recv(self.buffer_size)
result = packet.decode() if decode else packet
result = packet.decode() if self.decode else packet
self._outbox.put(result)
cast(self._bridge, "send", ("outbox", result))
except (BrokenPipeError, OSError) as e: