Skip to content

Instantly share code, notes, and snippets.

@pasoroki
Last active September 3, 2017 09:08
Show Gist options
  • Save pasoroki/e7970e1649f8b41296700c585d420d46 to your computer and use it in GitHub Desktop.
Save pasoroki/e7970e1649f8b41296700c585d420d46 to your computer and use it in GitHub Desktop.
Singleton sandbox
import logging
import types
from modules import module_helloworld
#####################################
# Bad
# from proxy_lib import ProxySingleton
# Good
from proxies.proxy_lib import ProxySingleton, get_modules, get_path, get_fake_module
#####################################
FORMAT = '[%(filename)20s] %(funcName)18s : %(message)s'
logging.basicConfig(format=FORMAT)
_logger = logging.getLogger(__name__)
_logger.setLevel(logging.INFO)
def start_execution():
ProxySingleton.action(data=1)
hello_world = module_helloworld.get_helloworld()
_logger.info(hello_world)
if __name__ == "__main__":
_logger.info("Modules:\n\t{}".format("\n\t".join(get_modules())))
_logger.info("Path:\n\t{}".format("\n\t".join(get_path())))
_logger.info("-"*30)
_logger.info("Starting execution")
ProxySingleton.setup(parameter=123)
start_execution()
from proxies.proxy_lib import ProxySingleton
import sys
import logging
_logger = logging.getLogger(__name__)
_logger.setLevel(logging.INFO)
sys.path.insert(0, "proxies")
def get_helloworld():
_logger.info("Triggering Hello World")
ProxySingleton.action(data=2)
return "Hello world!"
from sys import modules, path
import types
import logging
_logger = logging.getLogger(__name__)
_logger.setLevel(logging.INFO)
def get_modules(name="proxy_lib"):
result = []
for module_name in modules.keys():
if name.lower() in module_name.lower():
result.append("\t> {:20} : {}".format(module_name, modules[module_name]))
return result
def get_path():
result = []
for dir in path:
if dir.startswith("/usr"):
continue
result.append("\t- {}".format(dir))
return result
class ProxySingleton(object):
activated = False
parameter = None
@classmethod
def setup(cls, parameter):
cls.parameter = parameter
cls.activated = True
_logger.info("[ID:{}] Proxy service activated".format(id(cls)))
@classmethod
def action(cls, data):
if not cls.activated:
_logger.info("[ID:{}] Proxy is not activated. Skipping".format(id(cls)))
return
old_parameter = cls.parameter
cls.parameter = data
new_parameter = cls.parameter
_logger.info("[ID:{}] Successfully executed action. Changed parameter from {} to {}".format(
id(cls),
old_parameter,
new_parameter
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment