mirror of
https://github.com/ets-labs/python-dependency-injector.git
synced 2024-11-25 19:14:00 +03:00
Adding @inject() decorator examples
This commit is contained in:
parent
4ccf38942b
commit
c19a7ed400
38
examples/advanced_usage/inject_decorator_flask.py
Normal file
38
examples/advanced_usage/inject_decorator_flask.py
Normal file
|
@ -0,0 +1,38 @@
|
||||||
|
"""`@inject` decorator and Flask view example."""
|
||||||
|
|
||||||
|
import sqlite3
|
||||||
|
|
||||||
|
from flask import Flask
|
||||||
|
|
||||||
|
from objects.providers import Singleton
|
||||||
|
from objects.injections import KwArg
|
||||||
|
from objects.injections import Attribute
|
||||||
|
from objects.injections import inject
|
||||||
|
|
||||||
|
|
||||||
|
# Database and `ObjectA` providers.
|
||||||
|
database = Singleton(sqlite3.Connection,
|
||||||
|
KwArg('database', ':memory:'),
|
||||||
|
KwArg('timeout', 30),
|
||||||
|
KwArg('detect_types', True),
|
||||||
|
KwArg('isolation_level', 'EXCLUSIVE'),
|
||||||
|
Attribute('row_factory', sqlite3.Row))
|
||||||
|
|
||||||
|
# Flask application:
|
||||||
|
app = Flask(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
# Flask view with @inject decorator:
|
||||||
|
@app.route('/')
|
||||||
|
@inject(KwArg('database', database))
|
||||||
|
def hello(database):
|
||||||
|
"""Example Flask view."""
|
||||||
|
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>
|
18
examples/advanced_usage/inject_decorator_simple.py
Normal file
18
examples/advanced_usage/inject_decorator_simple.py
Normal file
|
@ -0,0 +1,18 @@
|
||||||
|
"""`@inject()` decorator simple example."""
|
||||||
|
|
||||||
|
from objects.providers import Factory
|
||||||
|
from objects.injections import KwArg
|
||||||
|
from objects.decorators import inject
|
||||||
|
|
||||||
|
|
||||||
|
objects_factory = Factory(object)
|
||||||
|
|
||||||
|
|
||||||
|
@inject(KwArg('new_object', objects_factory))
|
||||||
|
@inject(KwArg('some_setting', 1334))
|
||||||
|
def example_callback(new_object, some_setting):
|
||||||
|
"""Example callback that does some asserts with input args."""
|
||||||
|
assert isinstance(new_object, object)
|
||||||
|
assert some_setting == 1334
|
||||||
|
|
||||||
|
example_callback()
|
Loading…
Reference in New Issue
Block a user