Trainspotting - Python Dependency Injector based on interface binding

Overview

trainspotting

Choose dependency injection

  • Friendly with MyPy
  • Supports lazy injections
  • Supports fabrics with environment variables
  • Can connect/disconnect clients in correct order

Install

pip install trainspotting

Contact

Feel free to ask questions in telegram t.me/PulitzerKenny

Examples

from typing import Protocol
from dataclasses import dataclass
from trainspotting import DependencyInjector
from trainspotting.factory import factory, EnvField


class TransportProtocol(Protocol):
    def go(self): ...

class EngineProtocol(Protocol):
    def start(self): ...

class HeadlightsProtocol(Protocol):
    def light(self): ...

@dataclass
class Driver:
    transport: TransportProtocol
    
    def drive(self):
        self.transport.go()

@dataclass
class V8Engine:
    sound: str

    def start(self):
        print(self.sound)

@dataclass
class XenonHeadlights:
    brightness: int

    def light(self):
        print(f'LIGHT! {self.brightness}')

@dataclass
class Car:
    engine: EngineProtocol
    headlights: HeadlightsProtocol

    def go(self):
        self.engine.start()
        self.headlights.light()

def get_config():
    return {
        EngineProtocol: factory(V8Engine, sound=EnvField('ENGINE_SOUND')),
        HeadlightsProtocol: factory(
            XenonHeadlights, 
            brightness=EnvField('HEADLIGHTS_BRIGHTNESS', int)
        ),
        TransportProtocol: Car,
    }

injector = DependencyInjector(get_config())
injected_driver = injector.inject(Driver)
injected_driver().drive()

Clients connect/disconnect

Connect can be used for async class initialization

import aioredis

from typing import Protocol
from trainspotting import DependencyInjector

class ClientProtocol(Protocol):
    async def do(self):
        ...

class RedisClient:
    def __init__(self):
        self.pool = None
        
    async def do(self):
        if not self.pool:
            raise ValueError
        print('did something')
    
    async def connect(self):
        self.pool = await aioredis.create_redis_pool(('127.0.0.1', 6379))
        print('connected')
        
    async def disconnect(self):
        self.pool.close()
        await self.pool.wait_closed()
        print('disconnected')


async def main(client: ClientProtocol):
    await client.do()


injector = DependencyInjector({ClientProtocol: RedisClient})
injected = injector.inject(main)

async with injector.deps:  # connected
    await injected() # did something
# disconnected

Types Injection

class EntityProtocol(Protocol):
    def do(self): ...

class Entity:
    def do(self):
        print('do something')

@dataclass
class SomeUsefulClass:
    entity: Type[EntityProtocol]

injector.add_config({EntityProtocol: Entity})
injector.inject(SomeUsefulClass)

Lazy injections

@injector.lazy_inject
async def some_func(client: ClientProtocol):
    await client.do_something()


some_func()  # raise TypeError, missing argument client
injector.do_lazy_injections()
some_func()  # ok

Extend or change config

injector.add_config({ClientProtocol: Client})

EnvField

import os
from typing import Protocol
from dataclasses import dataclass
from trainspotting import DependencyInjector
from trainspotting.factory import factory, EnvField


class ClientProtocol(Protocol):
    def do(self):
        ...


@dataclass
class Client(ClientProtocol):
    url: str
    log_prefix: str
    timeout: int = 5

    def do(self):
        print(f'{self.log_prefix}: sent request to {self.url} with timeout {self.timeout}')


injector = DependencyInjector({
    ClientProtocol: factory(
        Client,
        url=EnvField('SERVICE_URL'),
        log_prefix=EnvField('LOG_PREFIX', default='CLIENT'),
        timeout=EnvField('SERVICE_TIMEOUT', int, optional=True),
    )
})


def main(client: ClientProtocol):
    client.do()
    
    
os.environ.update({'SERVICE_URL': 'some_url'})
injected = injector.inject(main)
injected()  # CLIENT: sent request to some_url with timeout 5

Supports type validation

from typing import Protocol, runtime_checkable
from trainspotting import DependencyInjector


@runtime_checkable
class ClientProtocol(Protocol):
    def do(self):
        ...


class Client:
    def do(self):
        print('did something')


class BadClient:
    def wrong_do(self):
        ...
    

def main(client: ClientProtocol):
    client.do()

injector = DependencyInjector({
    ClientProtocol: BadClient,
})

injector.inject(main)()  # raise InjectionError: 
   
     does not realize 
    
      interface
    
   

injector = DependencyInjector({
    ClientProtocol: Client,
})

injector.inject(main)()  # prints: did something
Owner
avito.tech
avito.ru engineering team open source projects
avito.tech
High level cheatsheet that was designed to make checks on the OSCP more manageable

High level cheatsheet that was designed to make checks on the OSCP more manageable. This repository however could also be used for your own studying or for evaluating test systems like on HackTheBox

Jacob Scheetz 89 Jan 01, 2023
Python library to prevent XSS(cross site scripting attach) by removing harmful content from data.

A tool for removing malicious content from input data before saving data into database. It takes input containing HTML with XSS scripts and returns va

2 Jul 05, 2022
PrivateRoom - Make your work private by building a system using arduino which instantly kills a program when someone enters your room/cabin

privateRoom Make your work private by building a system using arduino which instantly kills a program when someone enters your room/cabin STEPS: Uploa

Divyanshu Kumar 3 Nov 08, 2022
This is a js front-end encryption blasting account and password tools

Author:0xAXSDD By Gamma安全实验室 version:1.0 explain:这是一款用户绕过前端js加密进行密码爆破的工具,你无需在意js加密的细节,只需要输入你想要爆破url,以及username输入框的classname,password输入框的clas

75 Nov 25, 2022
Template for new OSINT command-line tools

OSINT cli tool skeleton Template for new OSINT command-line tools. Press button "Use this template" to generate your own tool repository. See INSTALL.

36 Dec 20, 2022
The Decompressoin tool for Vxworks MINIFS

MINIFS-Decompression The Decompression tool for Vxworks MINIFS filesystem. USAGE python minifs_decompression.py [target_firmware] The example of Mercu

8 Jan 03, 2023
Time Discretization-Invariant Safe Action Repetition for Policy Gradient Methods

Time Discretization-Invariant Safe Action Repetition for Policy Gradient Methods This repository is the official implementation of Seohong Park, Jaeky

Seohong Park 6 Aug 02, 2022
Tool-X is a kali linux hacking Tool installer.

Tool-X is a kali linux hacking Tool installer. Tool-X developed for termux and other Linux based systems. using Tool-X you can install almost 370+ hacking tools in termux app and other linux based di

Rajkumar Dusad 4.2k May 29, 2022
OpenPort scanner GUI tool (CNMAP)

CNMAP-GUI- OpenPort scanner GUI tool (CNMAP) as you know it is the advanced tool to find open port, firewalls and we also added here heartbleed scanni

9 Mar 05, 2022
evtx-hunter helps to quickly spot interesting security-related activity in Windows Event Viewer (EVTX) files.

Introduction evtx-hunter helps to quickly spot interesting security-related activity in Windows Event Viewer (EVTX) files. It can process a high numbe

NVISO 116 Dec 29, 2022
Kriecher is a simple Web Scanner which will run it's own checks for the OWASP

Kriecher is a simple Web Scanner which will run it's own checks for the OWASP top 10 https://owasp.org/www-project-top-ten/# as well as run a

1 Nov 12, 2021
This repository consists of the python scripts for execution and automation of vivid tasks.

Scripting.py is a repository being maintained to keep log of the python scripts that I create for automating and executing some of my boring manual task.

Prakriti Regmi 1 Feb 07, 2022
A python script to decrypt media files encrypted using the Android application 'Decrypting 'LOCKED Secret Calculator Vault''. Will identify PIN / pattern.

A python script to decrypt media files encrypted using the Android application 'Decrypting 'LOCKED Secret Calculator Vault''. Will identify PIN / pattern.

3 Sep 26, 2022
Compilation of resources and insights that helped me on my journey to data scientist

Compilation of resources and insights that helped me on my journey to data scientist

Conor Dewey 1.5k Jan 02, 2023
Seamless deployment and management of cybersecurity solutions 🏗️

Description 🖼️ Background 👴🏼 Vision 📜 Concepts 💬 Solutions' Lifecycle. Operations ⭕ Functionalities 🚀 Supported Cybersecurity Solutions 📦 Insta

MutableSecurity 36 Nov 10, 2022
MayorSec DNS Enumeration Tool

MayorSecDNSScan MSDNSScan is used to identify DNS records for target domains and check for zone transfers. There really isn't much special about it, a

Joe Helle 68 Dec 12, 2022
The self-hostable proxy tunnel

TTUN Server The self-hostable proxy tunnel. Running Running: docker run -e TUNNEL_DOMAIN=Your tunnel domain -e SECURE=True if using SSL ghcr.io/to

Tom van der Lee 2 Jan 11, 2022
CVE-2022-1388 F5 BIG-IP iControl REST Auth Bypass RCE

CVE-2022-1388 CVE-2022-1388 F5 BIG-IP iControl REST Auth Bypass RCE. POST /mgmt/tm/util/bash HTTP/1.1 Host: Accept-Encoding: gzip, deflate Accept: */

M4rtin Hsu 81 Dec 12, 2022
Sonoff NSPanel protocol and hacking information. Tasmota Berry driver for NSPanel

NSPanel Hacking Sonoff NSPanel protocol and hacking information and Tasmota Berry driver. NSPanel protocol manual Tasmota driver nspanel.be Installati

blakadder 98 Dec 26, 2022
The Multi-Tool Web Vulnerability Scanner.

🟥 RapidScan v1.2 - The Multi-Tool Web Vulnerability Scanner RapidScan has been ported to Python3 i.e. v1.2. The Python2.7 codebase is available on v1

skavngr 1.3k Dec 31, 2022