You can download this code by clicking the button below.
This code is now available for download.
The code defines a function that uses SQLAlchemy to create an in-memory database and generates a random user object with random name and age.
Technology Stack : The code uses the SQLAlchemy package and technology stack.
Code Type : The type of code
Code Difficulty : Advanced
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import random
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
def generate_random_user():
# This function generates a random user object with random name and age.
engine = create_engine('sqlite:///:memory:')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
random_name = ''.join(random.choices('ABCDEFGHIJKLMNOPQRSTUVWXYZ', k=5))
random_age = random.randint(18, 65)
user = User(name=random_name, age=random_age)
session.add(user)
session.commit()
return user