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
Providing DevOps and security teams script to identify cloud workloads that may be vulnerable to the Log4j vulnerability(CVE-2021-44228) in their AWS account.

We are providing DevOps and security teams script to identify cloud workloads that may be vulnerable to the Log4j vulnerability(CVE-2021-44228) in their AWS account. The script enables security teams

Mitiga 13 Jan 04, 2022
This repository uses a mixture of numbers, alphabets, and other symbols found on the computer keyboard

This repository uses a mixture of numbers, alphabets, and other symbols found on the computer keyboard to form a 16-character password which is unpredictable and cannot easily be memorised.

Mohammad Shaad Shaikh 1 Nov 23, 2021
Detection tool of malware(s) by checksum (useful for forensic)

🐍 malware_checker.py Detection tool of malware(s) by checksum (useful for forensic) 📦 Dependencies installation $ pip3 install -r requirements.txt

Fayred 1 Jan 30, 2022
CVE-2021-45232-RCE-多线程批量漏洞检测

CVE-2021-45232-RCE CVE-2021-45232-RCE-多线程批量漏洞检测 FOFA 查询 title="Apache APISIX Das

孤桜懶契 36 Sep 21, 2022
Grafana-POC(CVE-2021-43798)

Grafana-Poc 此工具请勿用于违法用途。 一、使用方法:python3 grafana_hole.py 在domain.txt中填入ip:port 二、漏洞影响范围 影响版本: Grafana 8.0.0 - 8.3.0 安全版本: Grafana 8.3.1, 8.2.7, 8.1.8,

8 Jan 03, 2023
A script to extract SNESticle from Fight Night Round 2

fn22snesticle.py A script for producing a SNESticle ISO from a Fight Night Round 2 ISO and any SNES ROM. Background Fight Night Round 2 is a boxing ga

Johannes Holmberg 57 Nov 22, 2022
Python-based proof-of-concept tool for generating payloads that utilize unsafe Java object deserialization.

Python-based proof-of-concept tool for generating payloads that utilize unsafe Java object deserialization.

Astro 9 Sep 27, 2022
CVE-log4j CheckMK plugin

CVE-2021-44228-log4j discovery (Download the MKP package) This plugin discovers vulnerable files for the CVE-2021-44228-log4j issue. To discover this

4 Jan 08, 2022
This tool was created in order to automate some basic OSINT tasks for penetration testing assingments.

This tool was created in order to automate some basic OSINT tasks for penetration testing assingments. The main feature that I haven't seen much anywhere is the downloadd google dork function where t

Tobias 5 May 31, 2022
Dahua IPC/VTH/VTO devices auth bypass exploit

CVE-2021-33044 Dahua IPC/VTH/VTO devices auth bypass exploit About: The identity authentication bypass vulnerability found in some Dahua products duri

Ashish Kunwar 23 Dec 02, 2022
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
MSDorkDump is a Google Dork File Finder that queries a specified domain name and variety of file extensions

MSDorkDump is a Google Dork File Finder that queries a specified domain name and variety of file extensions (pdf, doc, docx, etc), and downloads them.

Joe Helle 150 Jan 03, 2023
Python Password Generator

This is a console-based version of a password generator written with Python. The program generates a password based on numbers of letters, numbers, and symbols specified by the user. This is a simple

p.katekomol 1 Jan 24, 2022
Scans for Log4j versions effected by CVE-2021-44228

check_mkExtension to check for log4j2 CVE-2021-44228 This Plugin wraps around logpresso/CVE-2021-44228-Scanner (Apache License 2.0) How it works Run i

inett GmbH 4 Jun 30, 2022
Gitlab RCE - Remote Code Execution

Gitlab RCE - Remote Code Execution RCE for old gitlab version = 11.4.7 & 12.4.0-12.8.1 LFI for old gitlab versions 10.4 - 12.8.1 This is an exploit f

153 Nov 09, 2022
Apache OFBiz rmi反序列化EXP(CVE-2021-26295)

Apache OFBiz rmi反序列化EXP(CVE-2021-26295) 目前仅支持nc弹shell 将ysoserial.jar放置在同目录下,py3运行,根据提示输入漏洞url,你的vps地址和端口 第二次使用建议删除exp.ot 本工具仅用于安全测试,禁止未授权非法攻击站点,否则后果自负

15 Nov 09, 2022
Simple and easy framework for phishing 🎣

👋 It's in beta, I'm still building How to install Linux and Termux: Clone Rp: git clone https://github.com/J4c5/superfish.git Install the dependencie

Jack 4 Jan 27, 2022
Auto Tor Ip Changer

AutoTor Auto Tor Ip Changer for Linux! git clone https://github.com/Arest7/AutoTor cd AutoTor pip install -r requirements.txt python3 AutoTor.py follo

Ken Ryuguji 3 Jan 23, 2022
A way to analyse how malware and/or goodware samples vary from each other using Shannon Entropy, Hausdorff Distance and Jaro-Winkler Distance

A way to analyse how malware and/or goodware samples vary from each other using Shannon Entropy, Hausdorff Distance and Jaro-Winkler Distance

11 Nov 15, 2022
a cool, easily usable and customisable subdomains scanner

Subdah 🔎 another subdomains scanner. Installation ⚠️ Python 3.10 required ⚠️ $ git clone https://github.com/traumatism/subdah $ cd subdah $ pip3 inst

toast 14 Oct 18, 2022