I have a db connection, which need configuration. I want to use this connection in all flask apis. So normally I would do it like this:
app = Flask(__name__)
db = Database(config_obj)
@app.route('/')
def hello():
# a lot of code
username = db.get_data()
return 'Hello, {}!'.format(username)
But, since hello
could be very long, I want to move hello
function into some other file.
So I could have 2 files:
First:
app = Flask(__name__)
db = Database(config_obj)
app.config['db_connection'] = db
app.route('/')(hello)
Second:
from flask import current_app
def hello():
# a lot of code
db = current_app.config['db_connection']
username = db.get_data()
return 'Hello, {}!'.format(username)
But this does not seems to be a good idea... Thoughts?