diff --git a/examples/advanced_usage/inject_decorator_flask.py b/examples/advanced_usage/inject_decorator_flask.py new file mode 100644 index 00000000..8aac55bd --- /dev/null +++ b/examples/advanced_usage/inject_decorator_flask.py @@ -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 diff --git a/examples/advanced_usage/inject_decorator_simple.py b/examples/advanced_usage/inject_decorator_simple.py new file mode 100644 index 00000000..94d51896 --- /dev/null +++ b/examples/advanced_usage/inject_decorator_simple.py @@ -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()