def test_run(): obj_graph = pinject.new_object_graph(modules=None, classes=[SomeClass]) with pytest.raises(pinject.NothingInjectableForArgError): obj_graph.provide(SomeClass) obj_graph = pinject.new_object_graph(modules=None, classes=[SomeClass, Foo]) some_class = obj_graph.provide(SomeClass) assert some_class assert some_class.foo
def init_object_graph(self, config): self.app_binding_spec = AppBindingSpec(config) specs = [bs() for bs in BindingSpecMountPoint.plugins] specs.append(self.app_binding_spec) object_graph = new_object_graph(binding_specs=specs) self.app_binding_spec.add_object_graph(object_graph) return object_graph
def create_dependencies(config, log): flags = {"debug": config.get("debug")} class FlagsBindingSpec(BindingSpec): def configure(self, bind): bind("flags", to_instance=flags) class LogBindingSpec(BindingSpec): def configure(self, bind): bind("log", to_instance=log) binding_specs = [FlagsBindingSpec(), LogBindingSpec()] classes = [ App, AppHandlers, AppSettings, Lifecycle, ] obj_graph = new_object_graph(modules=None, classes=classes, binding_specs=binding_specs) return obj_graph.provide(Dependencies)
def process_order_di(): obj_graph = pinject.new_object_graph( binding_specs=[OrderContextBindingSpec()]) order_service = obj_graph.provide(OrderService) order = Order("order-123") order_service.process_order(order)
def cli(**kwargs): """ Build system for the OLinuXino boards \f :param kwargs: :return: """ # Check for package version if kwargs['version']: print("olimage: {}".format(olimage.__version__)) sys.exit(0) # Update environment environment.options.update(kwargs) if kwargs['output']: environment.paths['output'] = kwargs['output'] prepare_logging() prepare_tree() # Initialize the object graph environment.obj_graph = pinject.new_object_graph()
def create(self, date_list): class TestSymbolSources(SymbolSources): def __init__(self): self.values = pd.DataFrame({ 'close': np.linspace(start=1., stop=100., num=len(date_list)), 'date': date_list }) @property def sources(self): return [ SingleFinancialSymbolSource( namespace='test_ns', name='test', values_fetcher=lambda: self.values, security_type=SecurityType.STOCK_ETF, start_period=pd.Period(self.values['date'].min(), freq='D'), end_period=pd.Period(self.values['date'].max(), freq='D'), period=Period.DAY, currency=Currency.RUB) ] class BindingSpec(pinject.BindingSpec): def configure(self, bind): bind('symbol_sources', to_class=TestSymbolSources) obj_graph = pinject.new_object_graph(binding_specs=[BindingSpec()]) yapo_instance = obj_graph.provide(y.Yapo) return yapo_instance
def main(): cfg = Configuration() init_logging(cfg) init_k8s_client(cfg) log = logging.getLogger(__name__) signal.signal(signal.SIGUSR2, thread_dump_logger(log)) try: log.info( "fiaas-deploy-daemon starting with configuration {!r}".format(cfg)) binding_specs = [ MainBindings(cfg), DeployerBindings(), K8sAdapterBindings(), WebBindings(), SpecBindings(), PipelineBindings() if not cfg.disable_pipeline_consumer and cfg.has_service("kafka_pipeline") else FakeConsumerBindings(), CustomResourceDefinitionBindings() if cfg.enable_crd_support else DisabledCustomResourceDefinitionBindings(), UsageReportingBindings(), ] obj_graph = pinject.new_object_graph(modules=None, binding_specs=binding_specs) obj_graph.provide(Main).run() except BaseException: log.exception( "General failure! Inspect traceback and make the code better!")
def make_object_graph(cls, commands): bindings = [] goals = [] reporters = [] for command in commands: bindings.extend(command.get("bindings", [])) goals.extend(command.get("goals", [])) reporters.extend(command.get("reporters", [])) bindings.append(ListBindingSpec("goals", goals)) bindings.append( ListBindingSpec("reporters", reporters or [flatsurvey.reporting.Log])) from random import randint bindings.append(FactoryBindingSpec("lot", lambda: randint(0, 2**64))) return pinject.new_object_graph( modules=[ flatsurvey.reporting, flatsurvey.surfaces, flatsurvey.jobs, flatsurvey.cache, ], binding_specs=bindings, )
def test_to_instance(): """ Tim: Demonstrate that the same data structure is shared across all instances of SomeClass.foo.""" obj_graph = pinject.new_object_graph(binding_specs=[MyBindingSpec()]) some_class1 = obj_graph.provide(SomeClass) some_class2 = obj_graph.provide(SomeClass) some_class1.foo['C'] = 67 assert some_class2.foo['C'] == 67
def main(): logging.basicConfig( format='%(asctime)s [ %(name)20s ]\t%(levelname)7s\t%(message)s') logging.root.setLevel(logging.INFO) obj_graph = pinject.new_object_graph(binding_specs=[RootModuleSpec()], modules=[systems, states]) obj_graph.provide(MainGame)
def test(): obj_graph = pinject.new_object_graph( binding_specs=[SomeBindingSpec()], only_use_explicit_bindings=True) with pytest.raises(pinject.NonExplicitlyBoundClassError): obj_graph.provide(ImplicitlyBoundClass) some_class = obj_graph.provide(ExplicitlyBoundClass) assert some_class.foo
def DeleteUserData(self, id): obj_graph = pinject.new_object_graph( binding_specs=[UserServiceBindingSpec()]) service: UserService = obj_graph.provide(UserServiceImp) if service.deleteUser(id): return make_response({"status": "success"}, 200) return make_response({"status": "failed"}, 422)
def web_graph(*extra_specs): req_scope_module = request_scope.RequestScopeModule() specs = [req_scope_module, WebModule(req_scope_module.middleware), db.DbModule()] + list(extra_specs) return pinject.new_object_graph( binding_specs=specs, id_to_scope=req_scope_module.id_to_scope, is_scope_usable_from_scope=req_scope_module.is_usable )
def obj_graph() -> ObjectGraphWrapper: global _obj_graph if _obj_graph is None: pinject_imports() pinject_obj_graph = pinject.new_object_graph( binding_specs=(DjangoProjectBindingSpec(), )) _obj_graph = ObjectGraphWrapper(pinject_obj_graph) return _obj_graph
def main(): obj_graph = pinject.new_object_graph() logging.warn("Creating iterator") iterator = obj_graph.provide( filereader.WindowIterator).configure('gutenberg/1/0/1/1016', 5) logging.warn("Creating vocab") vocab = IteratorAndVocab(iterator) logging.warn("Creating ae") ae = Autoencoder(500, 10000, 500) logging.warn("Training step") ae.train(vocab)
def handle(self, *args, **options): if len(args) == 0: print "Error! Please provide feed name in the first argument!" return use_cache = not options['nocache'] obj_graph = pinject.new_object_graph() clazz = self.get_class_by_feedname(args[0]) if clazz is not None: feed = obj_graph.provide(clazz) feed.gen_XML(use_cache) else: print "Feed name '%s' is not found" % args[0]
def create(): data = request.json email = data["email"] name = data["name"] obj_graph = pinject.new_object_graph( modules=None, classes=[UserController, UserRepository]) user_controller = obj_graph.provide(UserController) result = user_controller.create_user({"email": email, "name": name}) return handle_result(result)
def addUserProfileData(self): name = self.req.form['name'] username = self.req.form['username'] password = self.req.form['password'] profilePicture = self.req.files['profile_picture'] obj = pinject.new_object_graph( binding_specs=[UserDataServiceBinding()]) service: UserDataService = obj.provide(UserDataServiceImp) if service.addUser(name, username, password, profilePicture): return make_response({"status": "success"}, 200) return make_response({"status": "failed"}, 422)
def test__search_exact_finsym(): qry = 'micex/SBER' obj_graph = pinject.new_object_graph(binding_specs=[lib.BindingSpec()]) search_instance = obj_graph.provide(_Search) r = search_instance._check_finsym_access(query=qry) assert_that(r, not_none()) assert r.identifier_str == 'micex/SBER' rs = lib.search(query=qry) assert_that(rs, has_length(1)) assert rs[0].identifier_str == 'micex/SBER'
def UpdateUserData(self, id): name = self.req.form['name'] email = self.req.form['email'] shirtSize = self.req.form['shirt_size'] obj_graph = pinject.new_object_graph( binding_specs=[UserServiceBindingSpec()]) service: UserService = obj_graph.provide(UserServiceImp) if service.updateUser(id, name, email, shirtSize): return make_response({"status": "success"}, 200) return make_response({"status": "failed"}, 422)
def login(self): username = self.req.form['username'] password = self.req.form['password'] obj = pinject.new_object_graph( binding_specs=[UserDataServiceBinding()]) service: UserDataService = obj.provide(UserDataServiceImp) try: token = service.validateUser(username, password) except: return make_response({"status": "failed"}, 401) return make_response({"status": "success", "token": token}, 200)
def object_graph(self): """ :type Returns: """ og = pinject.new_object_graph(binding_specs=self._binding_specs, modules=list(self._modules), classes=self._classes) def call_with_injection(self, fn, *direct_pargs, **direct_kwargs): return self._obj_provider.call_with_injection(fn, self._injection_context_factory.new(fn), direct_pargs, direct_kwargs) def provide_class(self, clazz, *args, **kwargs): isclass = inspect.isclass(clazz) assert isclass arg_binding_key = arg_binding_keys.new(convert(clazz.__name__)) injection_context = self._injection_context_factory.new(clazz.__init__) super_classes = [c for c in inspect.getmro(clazz) if (inspect.isclass(c) and inspect.ismethod(c.__init__))] super_kwargs = dict() for c in super_classes: print c, inspect.isclass(c) __, k = self._obj_provider.get_injection_pargs_kwargs(c.__init__, injection_context, (), {}) super_kwargs.update(k) super_kwargs.update(kwargs) c = self._obj_provider.provide_from_arg_binding_key(clazz, arg_binding_key, injection_context, pargs=args, kwargs=super_kwargs) return c #self._obj_provider.provide_class(c, injection_context, direct_init_pargs=args, direct_init_kwargs=kwargs) def inject_method(self, fn, *args, **kwargs): isclass = inspect.isclass(fn) fn_to_call = fn.__init__ if isclass else fn injection_context = self._injection_context_factory.new(fn_to_call) pargs, kwargs = self._obj_provider.get_injection_pargs_kwargs(fn_to_call, injection_context, args, kwargs) log.info("Injecting %s" % str(fn)) log.info("pargs %s" % str(pargs)) log.info("kwargs %s" % str(kwargs)) return functools.partial(fn, *pargs, **kwargs) ## MONKEY PATCHING HAHAHAHA monkey_patch_instance(og, 'call_with_injection', call_with_injection) monkey_patch_instance(og, 'inject_method', inject_method) monkey_patch_instance(og, 'provide_class', provide_class) self._object_graph_initialised = True return og
def main(): parser = argparse.ArgumentParser() parser.add_argument("-p", "--port", type=int, default=13337) parser.add_argument("--debug", action="store_true", help="Enable debug features") args = parser.parse_args() loglevel = logging.INFO if args.debug: loglevel = logging.DEBUG logging.basicConfig(level=loglevel) obj_graph = pinject.new_object_graph( modules=None, binding_specs=[ObjectGraph(args.port, args.debug)]) game_server = obj_graph.provide(GameServer) game_server.run()
def main(argv): """Program entry point. :param argv: command-line arguments :type argv: :class:`list` """ # Setup pinject. obj_graph = pinject.new_object_graph(binding_specs=[IbsubBindingSpec()]) # TODO Not the cleanest solution. ibsub.obj_graph = obj_graph # Setup signal handlers. _install_sigint_handler() # Run pinject-provided main. return obj_graph.provide(Main)(argv)
def main(): obj_graph = pinject.new_object_graph(binding_specs=[SomeBindingSpec()]) service = obj_graph.provide(ExecuterService) response = service.execute() assert isinstance(service, ExecuterService) assert isinstance(service.settings, Settings) assert isinstance(service.service, BookService) assert isinstance(service.service.settings, Settings) assert isinstance(service.service.service, OrderService) assert isinstance(service.service.service.settings, Settings) assert "Hello from .env file" == response assert service.settings is service.service.settings assert service.settings is service.service.service.settings print(response)
def main(): cfg = Configuration() init_logging(cfg) init_k8s_client(cfg) log = logging.getLogger(__name__) try: log.info("fiaas-deploy-daemon starting with configuration {!r}".format(cfg)) binding_specs = [ MainBindings(cfg), DeployerBindings(), K8sAdapterBindings(), SpecBindings(), ] obj_graph = pinject.new_object_graph(modules=None, binding_specs=binding_specs) obj_graph.provide(Main).run() except BaseException: log.exception("General failure! Inspect traceback and make the code better!") sys.exit(1)
def __init__(self, config, exclude_injectable_module_paths): self.config = config self._instance_bindings = { o['name']: locate(o['path'])(**(o.get('options', {}))) for o in config['dart'].get('app_context', []) } self._instance_bindings.update({'dart_config': config}) this_dir = os.path.dirname(os.path.abspath(__file__)) dart_src_root = os.path.abspath(os.path.join(this_dir, '..', '..')) self.obj_graph = pinject.new_object_graph( modules=None, classes=find_injectable_classes([dart_src_root], exclude_injectable_module_paths or []), binding_specs=[DartBindingSpec(self._instance_bindings)] ) for obj in config['dart'].get('app_context', []): instance = self._instance_bindings[obj['name']] if hasattr(instance, 'set_app_context'): instance.set_app_context(self)
def __init__(self, config, exclude_injectable_module_paths): self.config = config self._instance_bindings = { o['name']: locate(o['path'])(**(o.get('options', {}))) for o in config['dart'].get('app_context', []) } self._instance_bindings.update({'dart_config': config}) this_dir = os.path.dirname(os.path.abspath(__file__)) dart_src_root = os.path.abspath(os.path.join(this_dir, '..', '..')) self.obj_graph = pinject.new_object_graph( modules=None, classes=find_injectable_classes([dart_src_root], exclude_injectable_module_paths or []), binding_specs=[DartBindingSpec(self._instance_bindings)]) for obj in config['dart'].get('app_context', []): instance = self._instance_bindings[obj['name']] if hasattr(instance, 'set_app_context'): instance.set_app_context(self)
def get_obj_graph(): _global = managers+ \ handlers+ \ [SwitchSNMPNetworkManager, ElasticSearchRepository]+ \ [TransactionSQLRepository, AccountTypeSQLRepository, AccountSQLRepository, PaymentMethodSQLRepository, CashboxSQLRepository, ProductSQLRepository]+ \ [MemberSQLRepository, MembershipSQLRepository, MailinglistSQLReposiroty, CharterSQLRepository] + \ [DeviceSQLRepository, IPSQLAllocator] + \ [PingSQLRepository, VLANSQLRepository, RoomSQLRepository] + \ [PortSQLRepository, SwitchSQLRepository] + \ [RoleSQLRepository, ApiKeySQLRepository] _base_interfaces = [ abc.ABC, CRUDManager, CRUDRepository, DefaultHandler, object ] def get_base_class(cls): if len(cls.__bases__) == 0 or set(_base_interfaces)&set(cls.__bases__): return cls return get_base_class(cls.__bases__[0]) _class_name_to_abstract = { cls.__name__: get_base_class(cls) for cls in _global } def get_arg_names(class_name): if class_name in _class_name_to_abstract: class_name = _class_name_to_abstract[class_name].__name__ return pinject.bindings.default_get_arg_names_from_class_name(class_name) return pinject.new_object_graph( modules=None, classes=_global, get_arg_names_from_class_name=get_arg_names )
class EventSubscriberSpec(pinject.BindingSpec): def configure(self, bind): subscriber_config = CONFIG["ports"]["event_subscriber"] consumer = KafkaConsumer(subscriber_config["topic"], bootstrap_servers=subscriber_config["server"]) bind( "subscriber", to_instance=adapters.KafkaEventSubscriber(consumer=consumer), ) object_graph = pinject.new_object_graph( modules=None, binding_specs=[ EventPublisherSpec(), RequesterSpec(), ChecksReponsitorySpec(), EventSubscriberSpec(), ], ) class Application: check_availability: CheckAvailability collect_check_results: CollectCheckResults def __init__(self): self.check_availability = object_graph.provide(CheckAvailability) self.collect_check_results = object_graph.provide(CollectCheckResults)
def test_new_object_graph_works(self): class SomeClass(object): pass obj_graph = pinject.new_object_graph(classes=[SomeClass]) self.assertIsInstance(obj_graph.provide(SomeClass), SomeClass)
def main(): obj_graph = pinject.new_object_graph() greeting = obj_graph.provide(Greeting) print greeting.say_hello("Todd")
from pinject import new_object_graph from service.config import ConfigService obj_graph = new_object_graph(modules=None, classes=[ConfigService]) config_service = obj_graph.provide(ConfigService)
import pinject from boto3.dynamodb.conditions import Key from sutd.trivia_bot.common.bindings import ALL_BINDINGS from sutd.trivia_bot.common.database import QuestionRepository from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import List import sutd.trivia_bot.common.database import sutd.trivia_bot.common.quizzer OBJ_GRAPH = pinject.new_object_graph( modules=[sutd.trivia_bot.common.database, sutd.trivia_bot.common.quizzer], binding_specs=ALL_BINDINGS, ) def lambda_handler(event, context): sample_question_ids: List[str] = event["sample_question_ids"] already_asked: List[str] = event["already_asked"] not_yet_asked = list(set(sample_question_ids) - set(already_asked)) question_repository: QuestionRepository = OBJ_GRAPH.provide( QuestionRepository) question_id_to_ask = random.choice(not_yet_asked) question_to_ask = question_repository.find(question_id_to_ask)
def handle(self, *args, **options): use_cache = not 'nocache' in args obj_graph = pinject.new_object_graph() feed = obj_graph.provide(YandexXML) feed.gen_XML(use_cache)
class BindingSpec(pinject.BindingSpec): def configure(self, bind): bind('symbol_sources', to_class=AllSymbolSources) obj_graph = pinject.new_object_graph( binding_specs=[BindingSpec()], modules=[ cifrum.common, cifrum._index, cifrum._portfolio, cifrum._sources.registries, cifrum._sources.all_sources, cifrum._sources.base_classes, cifrum._sources.inflation_source, cifrum._sources.micex_stocks_source, cifrum._sources.moex_indexes_source, cifrum._sources.mutru_funds_source, cifrum._sources.okama_source, cifrum._sources.single_financial_symbol_source, cifrum._sources.us_data_source, cifrum._sources.yahoo_indexes_source, cifrum._portfolio.currency, cifrum._portfolio.portfolio, cifrum._search, ]) cifrum_instance = obj_graph.provide(Cifrum) information = cifrum_instance.information portfolio = cifrum_instance.portfolio portfolio_asset = cifrum_instance.portfolio_asset
import pinject class OuterClass(object): def __init__(self, inner_class): self.inner_class = inner_class pass class InnerClass(object): def __init__(self): self.forty_two = 42 pass obj_graph = pinject.new_object_graph() outer_class = obj_graph.provide(OuterClass) print outer_class.inner_class.forty_two
def __init__(self, config): super(Daemon, self).__init__(config) self.set_logger_name("daemon") self.__runtime = pinject.new_object_graph().provide(Runtime)
def test(): obj_graph = pinject.new_object_graph(binding_specs=[BindingSpecTwo()]) class_two = obj_graph.provide(ClassTwo) assert class_two.foobar == 'foo--bar'
class ShortBindingSpec(pinject.BindingSpec): def provide_data_store(self, config): return redis.Redis(config.get('host'), config.get('port')) def provide_config(self): # fetch config from file return {'host': '127.0.0.1', 'port': 6379} if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) # not satisfied with this API yet graph = pinject.new_object_graph(binding_specs=[ShortBindingSpec()]) short_endpoint = graph.provide(ShorteningEndpoint) root_router = Router([ Route('/', short_endpoint, 'index', methods=['GET']), Route('/', short_endpoint, 'new_url', methods=['POST']), Route('/<short_id>\+', short_endpoint, 'details'), Route('/<short_id>', short_endpoint, 'follow_url'), ]) app_container = AppContainer(root_router) from werkzeug.serving import run_simple run_simple('127.0.0.1', 5000, app_container.wsgi_app, use_reloader=True, use_debugger=True)
import pinject from sutd.trivia_bot.common.models import Question from sutd.trivia_bot.common.database import QuestionRepository from sutd.trivia_bot.common.bindings import ALL_BINDINGS from sutd.trivia_bot.data.mcq import questions as mcq_questions from sutd.trivia_bot.data.open import questions as open_questions if __name__ == "__main__": OBJ_GRAPH = pinject.new_object_graph(modules=None, binding_specs=ALL_BINDINGS) question_repository: QuestionRepository = OBJ_GRAPH.provide( QuestionRepository) # delete all questions question_repository.truncate() for i, mcq_question in enumerate(mcq_questions): if "question" not in mcq_question: raise ValueError(f"question attribute missing in index {i}") if "correct_answer" not in mcq_question: raise ValueError(f"correct_answer attribute missing in index {i}") if "wrong_answers" not in mcq_question: raise ValueError(f"wrong_answers attribute missing in index {i}") question = Question( id=f"mcq_{i}", question=mcq_question["question"], correct_answer=mcq_question["correct_answer"].lower(), other_answers=[a.lower() for a in mcq_question["wrong_answers"]], type=Question.QuestionType.mcq, )
def test(): obj_graph = pinject.new_object_graph(binding_specs=[SomeBindingSpec()]) some_class = obj_graph.provide(SomeClass) assert some_class.foo == 'foo-with-annot'
def test(): obj_graph = pinject.new_object_graph(binding_specs=[MyBindingSpec()]) some_class = obj_graph.provide(SomeClass) assert some_class.long_name.foo == 'foo' assert isinstance(some_class.long_name, SomeReallyLongClassName)
def test_good(): obj_graph = pinject.new_object_graph( binding_specs=[MainBindingSpec(), SatisfyingBindingSpec()])
def test_bad(): with pytest.raises(pinject.MissingRequiredBindingError): obj_graph = pinject.new_object_graph( binding_specs=[MainBindingSpec(), NonSatisfyingBindingSpec()]) # would raise a MissingRequiredBindingError
def test(): obj_graph = pinject.new_object_graph(binding_specs=[MainBindingSpec()]) some_class = obj_graph.provide(SomeClass) assert some_class.foo == 'a-real-foo'
"""Binding specs can declare dependencies.""" import pinject class ClassOne(object): def __init__(self, foo): self.foo = foo class ClassTwo(object): def __init__(self, class_one, bar): self.foobar = class_one.foo + bar class BindingSpecOne(pinject.BindingSpec): def configure(self, bind): bind('foo', to_instance='foo-') class BindingSpecTwo(pinject.BindingSpec): def configure(self, bind): bind('bar', to_instance='-bar') def dependencies(self): return [BindingSpecOne()] obj_graph = pinject.new_object_graph(binding_specs=[BindingSpecTwo()]) class_two = obj_graph.provide(ClassTwo) print class_two.foobar
def process_order_prototype(): obj_graph = pinject.new_object_graph( binding_specs=[OrderContextBindingSpec()]) order_service_1 = obj_graph.provide(OrderService) order_service_2 = obj_graph.provide(OrderService) print(order_service_1.order_context is order_service_2.order_context)
import pinject class OuterClass(object): def __init__(self, inner_class): self.inner_class = inner_class class InnerClass(object): def __init__(self): self.forty_two = 42 obj_graph = pinject.new_object_graph() outer_class = obj_graph.provide(OuterClass) print outer_class.inner_class.forty_two
""" If it takes more to instantiate a class than calling its initializer and injecting initializer args, then you can write a provider method for it. Pinject can use provider methods to instantiate objects used to inject as the values of other args. """ import pinject class SomeClass(object): def __init__(self, foo): self.foo = foo class SomeBindingSpec(pinject.BindingSpec): def provide_foo(self): return 'some-complex-foo' obj_graph = pinject.new_object_graph(binding_specs=[SomeBindingSpec()]) some_class = obj_graph.provide(SomeClass) print some_class.foo
from pinject import new_object_graph from service.config import ConfigService from service.spot_crud import SpotCrudService from service.spot_validation import SpotValidationService obj_graph = new_object_graph(modules=None, classes=[ConfigService, SpotCrudService, SpotValidationService]) config_service = obj_graph.provide(ConfigService) spot_crud_service = obj_graph.provide(SpotCrudService) spot_validation_service = obj_graph.provide(SpotValidationService)