You can download this code by clicking the button below.
This code is now available for download.
The code defines a function that creates a random user and saves it to a SQLite in-memory database.
Technology Stack : The code uses the SQLAlchemy library to interact with a database. It also utilizes the random library for generating random data.
Code Type : The type of code
Code Difficulty : Intermediate
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql import func
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():
# Create an in-memory SQLite database
engine = create_engine('sqlite:///:memory:')
Base.metadata.create_all(engine)
# Create a session
Session = sessionmaker(bind=engine)
session = Session()
# Generate a random user
random_user = User(name=random.choice(['Alice', 'Bob', 'Charlie']), age=random.randint(18, 60))
# Add the user to the session and commit
session.add(random_user)
session.commit()
# Close the session
session.close()
return random_user