Peewee-Based Database Operations for User Management

  • Share this:

Code introduction


This code defines a set of database operation functions based on Peewee, including creating a database, adding users, getting users by email, updating user emails, deleting users, listing all users, and counting users.


Technology Stack : Peewee, SQLite

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import random

from peewee import *

# Define the database
db = SqliteDatabase('my_database.db')

# Define a model for the user
class User(Model):
    username = CharField()
    email = CharField()

    class Meta:
        database = db

# Function to add a user to the database
def add_user(username, email):
    # Create a new user instance
    new_user = User(username=username, email=email)
    # Save the user to the database
    new_user.save()

# Function to get a user by email
def get_user_by_email(email):
    # Query the database for a user with the given email
    user = User.select().where(User.email == email).get()
    return user

# Function to update a user's email
def update_user_email(username, new_email):
    # Update the user's email
    User.update(email=new_email).where(User.username == username).execute()

# Function to delete a user
def delete_user(username):
    # Delete the user from the database
    User.delete().where(User.username == username).execute()

# Function to list all users
def list_all_users():
    # Get all users from the database
    users = User.select()
    return users

# Function to count the number of users
def count_users():
    # Get the count of all users in the database
    count = User.select().count()
    return count

# Function to create the database and tables
def create_database():
    # Create the database file
    db.connect()
    # Create tables if they don't exist
    db.create_tables([User])

# Function to drop the database and tables
def drop_database():
    # Drop the tables
    db.drop_tables([User])
    # Close the database connection
    db.close()

# Example usage
if __name__ == "__main__":
    create_database()
    add_user('john_doe', 'john@example.com')
    user = get_user_by_email('john@example.com')
    print(user.email)
    update_user_email('john_doe', 'john_new@example.com')
    delete_user('john_doe')
    print(list_all_users())
    print(count_users())
    drop_database()                
              
Tags: