You can download this code by clicking the button below.
This code is now available for download.
This function creates a random user and adds it to the database.
Technology Stack : Flask, Flask-SQLAlchemy
Code Type : Function
Code Difficulty : Intermediate
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import random
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
db = SQLAlchemy(app)
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)
def create_random_user():
username = f"user{random.randint(1, 100)}"
email = f"{username}@example.com"
new_user = User(username=username, email=email)
db.session.add(new_user)
db.session.commit()