Creating Users with Peewee and SQLite Database

  • Share this:

Code introduction


This function uses the Peewee library to create a new user and save it to a SQLite database. If the user already exists, it returns an error message.


Technology Stack : Peewee, SQLite

Code Type : Database operation

Code Difficulty : Intermediate


                
                    
import peewee
from random import choice

# Create a custom Peewee model for a simple user
class User(peewee.Model):
    username = peewee.CharField()
    email = peewee.CharField()

    class Meta:
        database = peewee.SqliteDatabase('users.db')

# Function to create a new user and save it to the database
def create_user(username, email):
    try:
        # Connect to the database
        user_db = User.database.connect()
        
        # Create a new user
        new_user = User(username=username, email=email)
        
        # Save the new user to the database
        new_user.save()
        
        # Return a success message
        return f"User {username} created successfully."
    
    except peewee.IntegrityError:
        # Return an error message if the user already exists
        return f"User {username} already exists."
    
    finally:
        # Close the database connection
        user_db.close()

# JSON representation of the code                
              
Tags: