Skip to content

Instantly share code, notes, and snippets.

@automactic
Last active March 21, 2017 21:29
Show Gist options
  • Save automactic/f84a4cd95e5709f6db3c341337c74e3c to your computer and use it in GitHub Desktop.
Save automactic/f84a4cd95e5709f6db3c341337c74e3c to your computer and use it in GitHub Desktop.
A question

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)

Problem

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment