Forums

Flask Log In and sqlite problem

I'm getting the error:

AttributeError: '_RequestGlobals' object has no attribute 'db'

Here are parts of the code, please let me know if you need anything else:

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

def init_db():
    with closing(connect_db()) as db:
        with app.open_resource('schema.sql', mode='r') as f:
            db.cursor().executescript(f.read())
        db.commit()

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

@app.teardown_request
def teardown_request(exception):
    db = getattr(g, 'db', None)
    if db is not None:
        db.close()
@login_manager.user_loader
def load_user(email):
    c = g.db.execute("SELECT email,password from users where email = (?)", [email])
    userrow = c.fetchone()
    userid = User(userrow[0], userrow[1])
    return userid


2015-01-10 00:32:02,297 :Traceback (most recent call last):
2015-01-10 00:32:02,297 :  File "/bin/user_wsgi_wrapper.py", line 130, in __call__
2015-01-10 00:32:02,297 :    self.error_log_file.logger.exception("Error running WSGI application")
2015-01-10 00:32:02,297 :  File "/usr/lib/python2.7/logging/__init__.py", line 1185, in exception
2015-01-10 00:32:02,297 :    self.error(msg, *args, **kwargs)
2015-01-10 00:32:02,297 :  File "/usr/lib/python2.7/logging/__init__.py", line 1178, in error
2015-01-10 00:32:02,298 :    self._log(ERROR, msg, args, **kwargs)
2015-01-10 00:32:02,298 :  File "/usr/lib/python2.7/logging/__init__.py", line 1270, in _log
2015-01-10 00:32:02,298 :    record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info, func, extra)
2015-01-10 00:32:02,298 :  File "/usr/lib/python2.7/logging/__init__.py", line 1244, in makeRecord
2015-01-10 00:32:02,298 :    rv = LogRecord(name, level, fn, lno, msg, args, exc_info, func)
2015-01-10 00:32:02,298 :  File "/usr/lib/python2.7/logging/__init__.py", line 284, in __init__
2015-01-10 00:32:02,299 :    self.threadName = threading.current_thread().name
2015-01-10 00:32:02,299 :  File "/usr/lib/python2.7/threading.py", line 1160, in currentThread
2015-01-10 00:32:02,299 :    return _active[_get_ident()]
2015-01-10 00:32:02,299 :  File "/bin/user_wsgi_wrapper.py", line 122, in __call__
2015-01-10 00:32:02,299 :    app_iterator = self.app(environ, start_response)
2015-01-10 00:32:02,299 :  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1701, in __call__
2015-01-10 00:32:02,300 :    return self.wsgi_app(environ, start_response)
2015-01-10 00:32:02,300 :  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1689, in wsgi_app
2015-01-10 00:32:02,300 :    response = self.make_response(self.handle_exception(e))
2015-01-10 00:32:02,300 :  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1687, in wsgi_app
2015-01-10 00:32:02,300 :    response = self.full_dispatch_request()
2015-01-10 00:32:02,300 :  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1360, in full_dispatch_request
2015-01-10 00:32:02,301 :    rv = self.handle_user_exception(e)
2015-01-10 00:32:02,301 :  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1356, in full_dispatch_request
2015-01-10 00:32:02,301 :    rv = self.preprocess_request()
2015-01-10 00:32:02,301 :  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1539, in preprocess_request
2015-01-10 00:32:02,301 :    rv = func()
2015-01-10 00:32:02,302 :  File "/usr/local/lib/python2.7/dist-packages/flask_login.py", line 339, in _load_user
2015-01-10 00:32:02,302 :    self.reload_user()
2015-01-10 00:32:02,302 :  File "/usr/local/lib/python2.7/dist-packages/flask_login.py", line 367, in reload_user
2015-01-10 00:32:02,302 :    user = self.user_callback(user_id)
2015-01-10 00:32:02,302 :  File "/home/mritchie712/gather/gather.py", line 317, in load_user
2015-01-10 00:32:02,303 :    c = g.db.execute("SELECT email,password from users where email = (?)", [email])
2015-01-10 00:32:02,303 :  File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 336, in __getattr__
2015-01-10 00:32:02,303 :    return getattr(self._get_current_object(), name)
2015-01-10 00:32:02,303 :AttributeError: '_RequestGlobals' object has no attribute 'db'

Also, the db connection works fine in other places, it's only in the flask load_user that it breaks

This fixes the problem, but I don't think it's the right way to fix it

@login_manager.user_loader
def load_user(email):
    g.db = connect_db()
    c = g.db.execute("SELECT email,password from users where email = (?)", [email])
    userrow = c.fetchone()
    userid = User(userrow[0], userrow[1])
    return userid

Hi mritchie712,

I am not super familiar with flask, but I think the global variable g that flask creates in its application context only exists during request handling unless you explicitly specify it by putting codes within a context manager.

I think the user_loader decorator will call the load_user function before there is a request context. If you look at the error traceback, the user_loader is invoked during the preprocess_request stage, which is probably before/concurrent with the application context loading.

What happens when you try to access g.db with a @route('/random_url') function. Are you able to access that? Is it just the load_user function that fails?

You're the man.

The problem was with where I had the login_manager.... it was before my DB connection, thanks a ton!

login_manager = LoginManager()
login_manager.init_app(app)