Python Dependency Injection Framework

2019-01-21 02:03发布

Is there a framework equivalent to Guice (http://code.google.com/p/google-guice) for Python?

16条回答
Viruses.
2楼-- · 2019-01-21 02:21

Will leave my 5 cents here :)

https://pypi.python.org/pypi/dependency_injector

"""Pythonic way for Dependency Injection."""

from dependency_injector import providers
from dependency_injector import injections


@providers.DelegatedCallable
def get_user_info(user_id):
    """Return user info."""
    raise NotImplementedError()


@providers.Factory
@injections.inject(get_user_info=get_user_info)
class AuthComponent(object):
    """Some authentication component."""

    def __init__(self, get_user_info):
        """Initializer."""
        self.get_user_info = get_user_info

    def authenticate_user(self, token):
        """Authenticate user by token."""
        user_info = self.get_user_info(user_id=token + '1')
        return user_info


print AuthComponent
print get_user_info


@providers.override(get_user_info)
@providers.DelegatedCallable
def get_user_info(user_id):
    """Return user info."""
    return {'user_id': user_id}


print AuthComponent().authenticate_user(token='abc')
# {'user_id': 'abc1'}

UPDATED

Some time passed and Dependency Injector is a bit different now. It's better to start from Dependency Injector GitHub page for getting actual examples - https://github.com/ets-labs/python-dependency-injector

查看更多
Emotional °昔
3楼-- · 2019-01-21 02:21

If you prefer a really tiny solution there's a little function, it is just a dependency setter.

https://github.com/liuggio/Ultra-Lightweight-Dependency-Injector-Python

查看更多
淡お忘
4楼-- · 2019-01-21 02:26

I haven't used it, but the Spring Python framework is based on Spring and implements Inversion of Control.

There also appears to be a Guice in Python project: snake-guice

查看更多
在下西门庆
5楼-- · 2019-01-21 02:28

Spring Python is an offshoot of the Java-based Spring Framework and Spring Security, targeted for Python. This project currently contains the following features:

  • Inversion Of Control (dependency injection) - use either classic XML, or the python @Object decorator (similar to the Spring JavaConfig subproject) to wire things together. While the @Object format isn't identical to the Guice style (centralized wiring vs. wiring information in each class), it is a valuable way to wire your python app.
  • Aspect-oriented Programming - apply interceptors in a horizontal programming paradigm (instead of vertical OOP inheritance) for things like transactions, security, and caching.
  • DatabaseTemplate - Reading from the database requires a monotonous cycle of opening cursors, reading rows, and closing cursors, along with exception handlers. With this template class, all you need is the SQL query and row-handling function. Spring Python does the rest.
  • Database Transactions - Wrapping multiple database calls with transactions can make your code hard to read. This module provides multiple ways to define transactions without making things complicated.
  • Security - Plugin security interceptors to lock down access to your methods, utilizing both authentication and domain authorization.
  • Remoting - It is easy to convert your local application into a distributed one. If you have already built your client and server pieces using the IoC container, then going from local to distributed is just a configuration change.
  • Samples - to help demonstrate various features of Spring Python, some sample applications have been created:
    • PetClinic - Spring Framework's sample web app has been rebuilt from the ground up using python web containers including: CherryPy. Go check it out for an example of how to use this framework. (NOTE: Other python web frameworks will be added to this list in the future).
    • Spring Wiki - Wikis are powerful ways to store and manage content, so we created a simple one as a demo!
    • Spring Bot - Use Spring Python to build a tiny bot to manage the IRC channel of your open source project.
查看更多
登录 后发表回答