You can download this code by clicking the button below.
This code is now available for download.
This function uses the Peewee library to create a new user in the database, with a randomly generated username and email.
Technology Stack : Peewee, Python standard library (random, string)
Code Type : Database Operations
Code Difficulty : Intermediate
def create_random_user(db):
# This function creates a new user with a random username and email in a Peewee database
from peewee import Model, CharField, EmailField, fn
# Define the User model
class User(Model):
username = CharField()
email = EmailField()
class Meta:
database = db # Assuming 'db' is a Peewee database instance
# Generate a random username and email
import random
import string
username = ''.join(random.choices(string.ascii_lowercase + string.digits, k=10))
email = f"{username}@example.com"
# Create and save the user
new_user = User.create(username=username, email=email)
return new_user