mirror of
https://github.com/ets-labs/python-dependency-injector.git
synced 2024-11-22 09:36:48 +03:00
Add docs for usage of @inject decorator with classes
This commit is contained in:
parent
512544ea9f
commit
94b2dee48a
|
@ -18,10 +18,23 @@ called to provide injectable values.
|
|||
|
||||
Example:
|
||||
|
||||
.. literalinclude:: ../../examples/advanced_usage/inject_decorator_simple.py
|
||||
.. literalinclude:: ../../examples/advanced_usage/inject_simple.py
|
||||
:language: python
|
||||
|
||||
Example of usage ``@di.inject()`` decorator with Flask:
|
||||
|
||||
.. literalinclude:: ../../examples/advanced_usage/inject_decorator_flask.py
|
||||
.. literalinclude:: ../../examples/advanced_usage/inject_flask.py
|
||||
:language: python
|
||||
|
||||
|
||||
@inject decorator with classes
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
``@di.inject()`` could be applied for classes. In such case, it will look for
|
||||
class's ``__init__()`` method and pass injection to it. If decorated class has
|
||||
no ``__init__()`` method, appropriate ``di.Error`` will be raised.
|
||||
|
||||
Example of usage ``@di.inject()`` with Flask class-based view:
|
||||
|
||||
.. literalinclude:: ../../examples/advanced_usage/inject_flask_class_based.py
|
||||
:language: python
|
||||
|
|
|
@ -11,7 +11,7 @@ follows `Semantic versioning`_
|
|||
Development version
|
||||
-------------------
|
||||
|
||||
- No featues.
|
||||
- Add ``@di.inject`` functionality for decorating classes.
|
||||
|
||||
0.9.5
|
||||
-----
|
||||
|
|
42
examples/advanced_usage/inject_flask_class_based.py
Normal file
42
examples/advanced_usage/inject_flask_class_based.py
Normal file
|
@ -0,0 +1,42 @@
|
|||
"""`@di.inject()` decorator with classes example."""
|
||||
|
||||
import sqlite3
|
||||
import flask
|
||||
import flask.views
|
||||
import dependency_injector as di
|
||||
|
||||
|
||||
database = di.Singleton(sqlite3.Connection,
|
||||
database=':memory:',
|
||||
timeout=30,
|
||||
detect_types=True,
|
||||
isolation_level='EXCLUSIVE')
|
||||
|
||||
app = flask.Flask(__name__)
|
||||
|
||||
|
||||
@di.inject(database=database)
|
||||
@di.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>
|
Loading…
Reference in New Issue
Block a user