Query Username by Email in Database

  • Share this:

Code introduction


This function queries the database for a username based on the provided email address. If a matching user is found, it returns the username; if not, it returns None. If an exception occurs during the query, it returns the string representation of the exception.


Technology Stack : Flask, Flask-SQLAlchemy

Code Type : Database Query

Code Difficulty : Intermediate


                
                    
from flask_sqlalchemy import SQLAlchemy
import random

db = SQLAlchemy()

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

def get_random_user_by_email(email):
    try:
        user = User.query.filter_by(email=email).first()
        if user:
            return user.username
        else:
            return None
    except Exception as e:
        return str(e)