user1356863 user1356863 - 1 month ago 13
Python Question

Flask blueprint cannot read sqlite3 DATABASES from config file

I would like Python Flask to read from configuration file the location of the sqlite3 database name without explicitly writing database name. Templates used are: http://flask.pocoo.org/docs/0.11/patterns/sqlite3/ and http://flask.pocoo.org/docs/0.11/tutorial/dbcon/.

When I try to read 'DATABASE' from my config file I get the following error message:

File "/app/my_cool_app/app/init.py", line 42, in before_request
g.db = connect_db()

File "/app/my_cool_app/app/init.py", line 36, in connect_db
return sqlite3.connect(my_cool_app.config['DATABASE'])

AttributeError: 'Blueprint' object has no attribute 'config'

Here is my init.py code when I try to read from the configuration file and get the above error:

import sqlite3
from flask import Flask, g
from .views import my_cool_app

# create application
def create_app(debug=True):
app = Flask(__name__, instance_relative_config=True)
app.debug = debug
app.config.from_object('config')
app.config.from_pyfile('config.py')
app.register_blueprint(my_cool_app)
return app

def connect_db():
return sqlite3.connect(my_cool_app.config['DATABASE']) <= LINE 36

@my_cool_app.before_request
def before_request():
g.db = connect_db()

@my_cool_app.teardown_request
def teardown_request(exception):
db = getattr(g, 'db', None)
if db is not None:
db.close()


Here is my run.py (I don't change it):

from app import create_app
app = create_app()


Here is my init.py code that works when I explicitly write DB name (not what I want):

import sqlite3
from flask import Flask, g
from .views import my_cool_app
DATABASE='/app/myappname/my_sqlite3_database_name.db'

# create application
def create_app(debug=True):
app = Flask(__name__, instance_relative_config=True)
app.debug = debug
app.config.from_object('config')
app.config.from_pyfile('config.py')
app.register_blueprint(my_cool_app)
return app

def connect_db():
return sqlite3.connect(DATABASE)

Answer

Your my_cool_app is an instance of Blueprint which doesn't have a config attribute. You need to use current_app:

import sqlite3
from flask import Flask, g, current_app
from .views import my_cool_app

# create application
def create_app(debug=True):
    app = Flask(__name__, instance_relative_config=True)
    app.debug = debug
    app.config.from_object('config')
    app.config.from_pyfile('config.py')
    app.register_blueprint(my_cool_app)
    return app

def connect_db():
    return sqlite3.connect(current_app.config['DATABASE'])

@my_cool_app.before_request
def before_request():
    g.db = connect_db()

@my_cool_app.teardown_request
def teardown_request(exception):
    db = getattr(g, 'db', None)
    if db is not None:
        db.close()
Comments