Retrieving users from the database

Starting with the first point, we will need to add a new dependency method, get, which returns the user, given the email, if it exists.

First, add a new exception class in users.py:

class UserNotFound(Exception): 
    pass 

This is what we will raise in the event of the user not being found. Now we will update our imports to include the following:

from sqlalchemy.orm.exc import NoResultFound 

NoResultFound, as the name implies, is raised by SQLAlchemy when a requested object is not found in the database. Now we can add a new method to our UserWrapper class:

def get(self, email): query = self.session.query(User) # ① try: user = query.filter_by(email=email).one() # ② except NoResultFound: message = 'User not found ...

Get Python Programming Blueprints now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.