I do not really understand what's the problem with it? I would like to use Flask's before and after request functions, otherwise my sessions are not closed and then I get time outs. These are my app's settings please help me to understand why I get "AttributeError: '_AppCtxGlobals' object has no attribute 'db'":
app = Flask(__name__)
bcrypt = Bcrypt(app)
login_manager = LoginManager()
login_manager.init_app(app)
app.secret_key = 'somekey'
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:password@localhost/database'
db = SQLAlchemy(app)
from models import *
login_manager.login_message = 'Please login first.'
login_manager.login_view = 'authenticate'
#################################
#################################
@login_manager.user_loader
def load_user(user_id):
"""user_loader - A decorator to mark the function responsible for loading a user from whatever data source we use."""
return User.query.filter(User.id == int(user_id)).first()
@app.before_request
def before_request():
g.db.connect()
g.user = current_user
@app.after_request
def after_request(response):
"""Close the database connection after each request"""
g.db.close()
return response
You appear to be trying to combine the SQLite example from the Flask docs with the Flask-SQLAlchemy extension, but the two are not related. There is no
g.db
, you interact with the database with thedb
object.Remove the
before_request
andafter_request
functions.