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

34 lines
888 B
Python
Raw Normal View History

2015-11-23 20:14:50 +03:00
"""`inject()` decorator and Flask view example."""
2015-08-05 17:01:23 +03:00
import sqlite3
import flask
2015-08-05 17:01:23 +03:00
2015-11-23 20:14:50 +03:00
from dependency_injector import providers
from dependency_injector import injections
2015-08-05 17:01:23 +03:00
2015-11-23 20:14:50 +03:00
database = providers.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('/')
2015-11-23 20:14:50 +03:00
@injections.inject(database)
@injections.inject(flask.request)
def hello(request, database):
2015-08-05 17:01:23 +03:00
"""Example Flask view."""
print request
2015-08-05 17:01:23 +03:00
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>