You can download this code by clicking the button below.
This code is now available for download.
This function randomly selects a user from the database.
Technology Stack : flask-sqlalchemy
Code Type : Database Query Function
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)
def get_random_user():
# This function fetches a random user from the database.
try:
# Query all users from the database
users = User.query.all()
# If there are no users, return None
if not users:
return None
# Randomly select a user from the list
random_user = random.choice(users)
return random_user
except Exception as e:
print(f"An error occurred: {e}")
return None