Random User Management in Flask with SQLite

  • Share this:

Code introduction


This code defines a Flask application that includes a SQLite database and a user model. A random function is chosen, which can be to add a new user or to retrieve all users.


Technology Stack : Flask, SQLAlchemy

Code Type : Flask Function

Code Difficulty : Intermediate


                
                    
from flask import Flask, request, jsonify
import random
from flask_sqlalchemy import SQLAlchemy

def random_flask_function():
    # Initialize Flask app
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
    db = SQLAlchemy(app)

    # Define a simple User model
    class User(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        username = db.Column(db.String(80), unique=True, nullable=False)
        email = db.Column(db.String(120), unique=True, nullable=False)

    # Create the database and tables
    db.create_all()

    # Define a function to add a new user
    def add_user(username, email):
        new_user = User(username=username, email=email)
        db.session.add(new_user)
        db.session.commit()

    # Define a function to get all users
    def get_all_users():
        return User.query.all()

    # Randomly choose a function to return
    functions = {
        'add_user': add_user,
        'get_all_users': get_all_users
    }
    chosen_function = random.choice(list(functions.keys()))

    return functions[chosen_function]

# Example usage
if __name__ == "__main__":
    chosen_function = random_flask_function()
    if callable(chosen_function):
        chosen_function("JohnDoe", "johndoe@example.com")

# JSON output