Peewee In-Memory DB User Model with Random ID Generation

  • Share this:

Code introduction


This function uses the Peewee library to create an in-memory database, defines a user model, inserts a user, and generates a random user ID.


Technology Stack : Peewee, SQLite, random

Code Type : Function

Code Difficulty : Intermediate


                
                    
from peewee import *

# Create a custom Peewee function that generates a random user ID
def generate_random_user_id():
    # Define a Peewee model for a User
    class User(Model):
        id = IntegerField(primary_key=True)
        name = CharField()

    # Connect to an in-memory SQLite database
    db = SqliteDatabase(':memory:')

    # Create tables for the model
    db.connect()
    db.create_tables([User])

    # Insert a user into the database
    user = User(name='John Doe')
    user.save()

    # Generate a random user ID by generating a random number and converting it to a string
    random_user_id = str(random.randint(1, 1000000))

    # Return the generated user ID
    return random_user_id

# JSON representation of the code