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
Mass Check Vulnerable Log4j CVE-2021-44228

Log4j-CVE-2021-44228 Mass Check Vulnerable Log4j CVE-2021-44228 Introduction Actually I just checked via Vulnerable Application from https://github.co

Justakazh 6 Dec 28, 2022
A Superfast SMS & Call bomber for Linux And Termux !

A Superfast SMS & Call bomber for Linux And Termux !

Anubhav Kashyap 15 Feb 21, 2022
A Burp Pro extension that adds log4shell checks to Burp Scanner

scan4log4shell A Burp Pro extension that adds log4shell checks to Burp Scanner, written by Daniel Crowley of IBM X-Force Red. Installation To install

X-Force Red 26 Mar 15, 2022
JumpServer远程代码执行漏洞检测利用脚本

Jumpserver-EXP JumpServer远程代码执行漏洞检测利用脚本

Veraxy 181 Dec 20, 2022
TCP/UDP port scanner on python, usong scapy and multiprocessin

Port Scanner TCP/UDP port scanner on python, usong scapy and multiprocessing. Usage python3 scanner.py [OPTIONS] IP_ADDRESS [{tcp|udp}[/[PORT|PORT-POR

Egor Krokhin 1 Dec 05, 2021
Tools for investigating Log4j CVE-2021-44228

Log4jTools Tools for investigating Log4j CVE-2021-44228 FetchPayload.py (Get java payload from ldap path provided in JNDI lookup). Example command: Re

MalwareTech 91 Dec 29, 2022
对naabu的端口扫描结果,调用nmap进行指纹识别

naabu2nmap 对naabu的端口扫描结果,调用nmap进行指纹识别

Se7en 12 Nov 22, 2022
Password List Maker

Red-Key Red-Key Password List Maker Version 1.1.2 Created By FireKing255 -=Features=- Create Random Password List Create Password List Create Password

FireKing255 7 Dec 26, 2021
Dapunta Multi Brute Force Facebook - Crack Facebook With Login - Free

✭ DMBF CRACK Dibuat Dengan ❤️ Oleh Dapunta Author: - Dapunta Khurayra X ⇨ Fitur Login [✯] Login Token ⇨ Fitur Crack [✯] Crack Dari Teman, Public,

Dapunta ID 10 Oct 19, 2022
Patching - Interactive Binary Patching for IDA Pro

Patching - Interactive Binary Patching for IDA Pro Overview Patching assembly code to change the behavior of an existing program is not uncommon in ma

589 Dec 30, 2022
macOS persistence tool

PoisonApple Command-line tool to perform various persistence mechanism techniques on macOS. This tool was designed to be used by threat hunters for cy

Cyborg Security, Inc 212 Dec 29, 2022
Security-TXT is a python package for retrieving, parsing and manipulating security.txt files.

Security-TXT is a python package for retrieving, parsing and manipulating security.txt files.

Frank 3 Feb 07, 2022
A Telegram Bot to force users to join a specific channel before sending messages in a group.

Promoter A Telegram Bot to force users to join a specific channel before sending messages in a group. Introduction A Telegram Bot to force users to jo

Mr. Dynamic 1 Jan 27, 2022
Reverse engineered Parler API

Parler's unofficial API with all endpoints present in their iOS app as of 08/12/2020. For the most part undocumented, but the error responses are alre

393 Nov 26, 2022
A python tool capable of creating HUGE wordlists. Has the ability to add custom words for concatenation in any way you see fit.

A python tool capable of creating HUGE wordlists. Has the ability to add custom words for concatenation in any way you see fit.

Codex 9 Oct 05, 2022
Open-source keylogger write in python

Python open-source keylogger Language Python open-source keylogger using pynput module Using Install dependences in archive setup.py or install.sh in

Dio brando 4 Jan 15, 2022
CVE-2021-26084 Remote Code Execution on Confluence Servers

CVE-2021-26084 CVE-2021-26084 Remote Code Execution on Confluence Servers. Dork Fofa: app="ATLASSIAN-Confluence" Usage Show help information. python P

FQ Hsu 63 Dec 30, 2022
RedTeam-Security - In this repo you will get the information of Red Team Security related links

OSINT Passive Discovery Amass - https://github.com/OWASP/Amass (Attack Surface M

Abhinav Pathak 5 May 18, 2022
Brainly-Scrambler - Brainly Scrambler With Python

Brainly-Scrambler Untuk admin brainly jangan lupa pasang captcha mu Note: Kamu

8 Feb 24, 2022
Domain abuse scanner covering domainsquatting and phishing keywords.

🦷 monodon 🐋 Domain abuse scanner covering domainsquatting and phishing keywords. Setup Monodon is a Python 3.7+ programm. To setup on a Linux machin

2 Mar 15, 2022