python-dependency-injector/examples/advanced_usage/inject_flask.py

30 lines
735 B
Python
Raw Normal View History

2015-09-02 12:23:01 +03:00
"""`@di.inject()` decorator and Flask view example."""
2015-08-05 17:01:23 +03:00
import sqlite3
import flask
import dependency_injector as di
2015-08-05 17:01:23 +03:00
database = di.Singleton(sqlite3.connect,
':memory:',
timeout=30,
detect_types=True,
isolation_level='EXCLUSIVE')
2015-08-05 17:01:23 +03:00
app = flask.Flask(__name__)
2015-08-05 17:01:23 +03:00
@app.route('/')
@di.inject(database)
2015-08-05 17:01:23 +03:00
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>