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

34 lines
905 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
2016-06-03 18:05:47 +03:00
import dependency_injector.providers as providers
import dependency_injector.injections as 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>