Will Carroll
Will Carroll

Reputation: 105

Flask-SQLAlchemy query.get() throws exception when querying for nonexistent key

I am building a Flask app that needs to manage user logins and sessions. I have run into an unusual error when attempting to validate a user's session. I use Flask sessions to store the user's current sessionId, then the application uses the sessionId to look up the current session from a sessions table in the database.

This is the code generating the error:

session_id = flask.session.get("session_id", "")
session = models.Session.Session.query.get(session_id)

This is the error I get from SQLAlchemy:

File "/home/gunicorn/PROJECTNAME/PROJECTNAMEenv/lib/python3.4/site-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/gunicorn/PROJECTNAME/PROJECTNAMEenv/lib/python3.4/site-packages/flask/app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/home/gunicorn/PROJECTNAME/PROJECTNAMEenv/lib/python3.4/site-packages/flask/app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/home/gunicorn/PROJECTNAME/PROJECTNAMEenv/lib/python3.4/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/home/gunicorn/PROJECTNAME/PROJECTNAMEenv/lib/python3.4/site-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/gunicorn/PROJECTNAME/PROJECTNAMEenv/lib/python3.4/site-packages/flask/app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/gunicorn/PROJECTNAME/PROJECTNAMEenv/lib/python3.4/site-packages/flask/app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/gunicorn/PROJECTNAME/PROJECTNAMEenv/lib/python3.4/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/home/gunicorn/PROJECTNAME/PROJECTNAMEenv/lib/python3.4/site-packages/flask/app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/gunicorn/PROJECTNAME/PROJECTNAMEenv/lib/python3.4/site-packages/flask/app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/gunicorn/PROJECTNAME/routes.py", line 24, in index
    return controllers.index.indexController()
  File "/home/gunicorn/PROJECTNAME/controllers/index.py", line 17, in indexController
    session = models.Session.Session.query.get(session_id)
  File "/home/gunicorn/PROJECTNAME/PROJECTNAMEenv/lib/python3.4/site-packages/sqlalchemy/orm/query.py", line 831, in get
    return self._get_impl(ident, loading.load_on_ident)
  File "/home/gunicorn/PROJECTNAME/PROJECTNAMEenv/lib/python3.4/site-packages/sqlalchemy/orm/query.py", line 842, in _get_impl
    if len(ident) != len(mapper.primary_key):
TypeError: object of type 'NoneType' has no len()

It appears that when query.get() is run for an index that does not exist in the table, this error is thrown, though the API docs for Flask-SQLAlchemy state that it should return None in this case.

For reference, here is the code for my Session model:

class Session(db.Model):
     sessionId = db.Column(db.String(32), primary_key=True)
     userId = db.Column(db.Integer, db.ForeignKey('user.userId'), nullable=False)
     createdOn = db.Column(db.DateTime, server_default=db.func.now(), onupdate=db.func.now())

EDIT FOR COMPLETENESS: My directory structure is linked here. run.py is the file where the Flask() object is created and run.

Upvotes: 2

Views: 2865

Answers (1)

Filipe Amaral
Filipe Amaral

Reputation: 1723

That error happens when you pass None as parameter of get() method. You can verify if session_id variable is not None before querying

if session_id is not None:
    session = models.Session.Session.query.get(session_id)
else:
    # do something

or you can use the filter_by() method in conjunction with first() method:

session = models.Session.Session.query.filter_by(sessionId=session_id).first()

it will return None if not was found.

Upvotes: 6

Related Questions