Random User Creation with Peewee Database

  • Share this:

Code introduction


The code defines a function named `create_random_user` which generates a random username and email address, then creates a `User` instance and saves it to the Peewee database.


Technology Stack : Peewee, SQLite

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
from peewee import *
import random

# Create a Peewee database
db = SqliteDatabase('my_database.db')

# Define a Peewee model
class User(Model):
    username = CharField()
    email = CharField()

    class Meta:
        database = db

# Function to create a random user and save to the database
def create_random_user():
    # Generate random username and email
    username = f"user{random.randint(1000, 9999)}"
    email = f"{username}@example.com"
    
    # Create a new User instance
    new_user = User(username=username, email=email)
    
    # Save the user to the database
    new_user.save()

# Execute the function
create_random_user()                
              
Tags: