Skip to content

Instantly share code, notes, and snippets.

@cmstead
Created March 17, 2021 18:26
Show Gist options
  • Save cmstead/7604eb74bd4fc84732ee29693f7bb9d6 to your computer and use it in GitHub Desktop.
Save cmstead/7604eb74bd4fc84732ee29693f7bb9d6 to your computer and use it in GitHub Desktop.
Python DI with PyAutoDI
from os import path
from PyAutoDI import get_new_container, load_and_register_modules
def get_container():
sep = path.sep
app_container = get_new_container();
load_and_register_modules(
f"modules{sep}dependencies{sep}**{sep}*.py",
app_container,
base_directory=f".{sep}app")
return app_container
app_container = get_container()
from ...Interfaces.LoggerInterface import LoggerInterface
class DataAccess:
def __init__(self, logger=LoggerInterface): # connection_string_factory
self.logger = logger
def query(self, user_data):
self.validate_request(user_data)
self.logger.log(f"User provided input: {user_data}")
def validate_request(self, user_data):
# do something with user data and return a value
return True
def register(container):
container.register(DataAccess)
from ...Interfaces.LoggerInterface import LoggerInterface
class Logger(LoggerInterface):
def __init__(self):
pass
def log(self, message):
print(message)
def register(container):
container.register(Logger, interface=LoggerInterface)
from abc import ABC, abstractmethod
class LoggerInterface(ABC):
@abstractmethod
def log(self, message):
raise Exception("Log has not been implemented")
from container import app_container
import my_business_logic_thing
data_access_instance = app_container.build("data_access")
something_else = app_container.build("something_else")
something_else.do_something_else()
data_access_instance.query("Robert'); DROP TABLE Students; --")
# Bobby Tables wuz here
class SomethingElse:
def __init__(self, logger):
self.logger = logger
def do_something_else(self):
# do some businessy logic and log the outcome
self.logger.log("Business logic outcome")
def register(container):
container.register(SomethingElse)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment