Update examples for 3.0

This commit is contained in:
Roman Mogilatov 2016-11-02 18:22:17 +02:00
parent 3bd19a168a
commit 7ae0086a69
12 changed files with 12 additions and 222 deletions

View File

@ -1,33 +0,0 @@
"""`inject()` decorator and Flask view example."""
import sqlite3
import flask
import dependency_injector.providers as providers
import dependency_injector.injections as injections
database = providers.Singleton(sqlite3.connect,
':memory:',
timeout=30,
detect_types=True,
isolation_level='EXCLUSIVE')
app = flask.Flask(__name__)
@app.route('/')
@injections.inject(database)
@injections.inject(flask.request)
def hello(request, database):
"""Example Flask view."""
print request
one = database.execute('SELECT 1').fetchone()[0]
return 'Query returned {0}, db connection {1}'.format(one, database)
if __name__ == '__main__':
app.run()
# Example output of "GET / HTTP/1.1" is:
# Query returned 1, db connection <sqlite3.Connection object at 0x1057e4030>

View File

@ -1,43 +0,0 @@
"""`inject()` decorator with classes example."""
import sqlite3
import flask
import flask.views
import dependency_injector.providers as providers
import dependency_injector.injections as injections
database = providers.Singleton(sqlite3.Connection,
database=':memory:',
timeout=30,
detect_types=True,
isolation_level='EXCLUSIVE')
app = flask.Flask(__name__)
@injections.inject(database=database)
@injections.inject(some_setting=777)
class HelloView(flask.views.View):
"""Example flask class-based view."""
def __init__(self, database, some_setting):
"""Initializer."""
self.database = database
self.some_setting = some_setting
def dispatch_request(self):
"""Handle example request."""
one = self.database.execute('SELECT 1').fetchone()[0]
one *= self.some_setting
return 'Query returned {0}, db connection {1}'.format(one, database)
app.add_url_rule('/', view_func=HelloView.as_view('hello_view'))
if __name__ == '__main__':
app.run()
# Example output of "GET / HTTP/1.1" is:
# Query returned 777, db connection <sqlite3.Connection object at 0x1057e4030>

View File

@ -1,28 +0,0 @@
"""`inject()` decorator simple example."""
import dependency_injector.providers as providers
import dependency_injector.injections as injections
dependency_injector_factory = providers.Factory(object)
# Example of using `inject()` decorator keyword argument injections:
@injections.inject(new_object=dependency_injector_factory)
@injections.inject(some_setting=1334)
def example_callback1(new_object, some_setting):
"""Example callback that does some asserts for input args."""
assert isinstance(new_object, object)
assert some_setting == 1334
# Example of using `inject()` decorator with positional argument injections:
@injections.inject(dependency_injector_factory, 1334)
def example_callback2(new_object, some_setting):
"""Example callback that does some asserts for input args."""
assert isinstance(new_object, object)
assert some_setting == 1334
example_callback1()
example_callback2()

View File

@ -30,7 +30,7 @@ if __name__ == '__main__':
class _SequenceContainer1(SequencesContainer):
object_provider = providers.Factory(object)
except errors.Error as exception:
print exception
print(exception)
# <class '__main__._SequenceContainer1'> can contain only
# <class '__main__.SequenceProvider'> instances
@ -38,7 +38,7 @@ if __name__ == '__main__':
class _SequenceContainer2(SequencesContainer):
object_provider = SequenceProvider(object)
except errors.Error as exception:
print exception
print(exception)
# <class '__main__.SequenceProvider'> can provide only
# <class '_abcoll.Sequence'> instances

View File

@ -24,7 +24,7 @@ if __name__ == '__main__':
try:
sequences_container.object_provider = providers.Factory(object)
except errors.Error as exception:
print exception
print(exception)
# <dependency_injector.containers.DynamicContainer object at
# 0x107820ed0> can contain only <class '__main__.SequenceProvider'>
# instances
@ -32,7 +32,7 @@ if __name__ == '__main__':
try:
sequences_container.object_provider = SequenceProvider(object)
except errors.Error as exception:
print exception
print(exception)
# <class '__main__.SequenceProvider'> can provide only
# <class '_abcoll.Sequence'> instances

View File

@ -11,5 +11,5 @@ class ApiClient(object):
def call(self, operation, data):
"""Make some network operations."""
print 'API call [{0}:{1}], method - {2}, data - {3}'.format(
self.host, self.api_key, operation, repr(data))
print('API call [{0}:{1}], method - {2}, data - {3}'.format(
self.host, self.api_key, operation, repr(data)))

View File

@ -1,40 +0,0 @@
"""Pythonic way for Dependency Injection - Auth System."""
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'}

View File

@ -1,66 +0,0 @@
"""Pythonic way for Dependency Injection - callback-based IoC container."""
import sqlite3
from dependency_injector import containers
from dependency_injector import providers
from dependency_injector import injections
class UsersService(object):
"""Users service, that has dependency on database."""
def __init__(self, db):
"""Initializer."""
self.db = db
class AuthService(object):
"""Auth service, that has dependencies on users service and database."""
def __init__(self, db, users_service):
"""Initializer."""
self.db = db
self.users_service = users_service
class Services(containers.DeclarativeContainer):
"""IoC container of service providers."""
@providers.Singleton
def database():
"""Provide database connection.
:rtype: sqlite3.Connection
"""
return sqlite3.connect(':memory:')
@providers.Factory
@injections.inject(db=database)
def users(**kwargs):
"""Provide users service.
:rtype: UsersService
"""
return UsersService(**kwargs)
@providers.Factory
@injections.inject(db=database)
@injections.inject(users_service=users)
def auth(**kwargs):
"""Provide users service.
:rtype: AuthService
"""
return AuthService(**kwargs)
# Retrieving services:
users_service = Services.users()
auth_service = Services.auth()
# Making some asserts:
assert users_service.db is auth_service.db is Services.database()
assert isinstance(auth_service.users_service, UsersService)
assert users_service is not Services.users()
assert auth_service is not Services.auth()

View File

@ -7,9 +7,9 @@ import dependency_injector.providers as providers
even_filter = providers.Callable(filter, lambda x: x % 2 == 0)
odd_filter = providers.Callable(filter, lambda x: x % 2 != 0)
# Creating even and odd ranges using xrange() and filter providers:
even_range = even_filter(xrange(1, 10))
odd_range = odd_filter(xrange(1, 10))
# Creating even and odd ranges using range() and filter providers:
even_range = even_filter(range(1, 10))
odd_range = odd_filter(range(1, 10))
# Making some asserts:
assert even_range == [2, 4, 6, 8]

View File

@ -25,6 +25,6 @@ some_service_provider = ServiceProvider(SomeService)
try:
some_service_provider = ServiceProvider(object)
except errors.Error as exception:
print exception
print(exception)
# <class '__main__.ServiceProvider'> can provide only
# <class '__main__.BaseService'> instances

View File

@ -30,6 +30,6 @@ photos_service_provider = ServiceProvider(PhotosService)
try:
some_service_provider = ServiceProvider(object)
except errors.Error as exception:
print exception
print(exception)
# <class '__main__.ServiceProvider'> can provide only
# <class '__main__.BaseService'> instances

View File

@ -28,7 +28,7 @@ thread_factory = providers.Factory(threading.Thread,
if __name__ == '__main__':
# Create 10 threads for concurrent execution of example():
threads = []
for thread_number in xrange(10):
for thread_number in range(10):
threads.append(thread_factory(name='Thread{0}'.format(thread_number)))
# Start execution of all created threads: