Home > Software design >  Create a default guest user on flask run
Create a default guest user on flask run

Time:01-16

How can I create a default guest user with username guest and password equal to password when I start the web server; i.e. flask run?

The purpose of this default guest user is to be a demo user so that the actual user doesn't have to register and be able to test and tour the web app.

models.py

from flask_login import UserMixin

from app import bcrypt, db, login_manager


@login_manager.user_loader
def load_user(user_id: int):
    return User.query.get(user_id)


class User(db.Model, UserMixin):
    __tablename__ = "user"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, unique=True)
    username = db.Column(db.String(60), unique=True, nullable=False)
    password = db.Column(db.String(60), nullable=False)

    def __init__(self, username="guest", password="password"):
        self.username = username
        self.password = bcrypt.generate_password_hash(password).decode("UTF-8")

    def __repr__(self):
        return f"<User {self.username!r}>"

    @classmethod
    def authenticate(cls, username, password):
        user = cls.query.filter_by(username=username).first()
        if user and bcrypt.check_password_hash(user.password, password):
            return user
        return False

views.py

from flask import Blueprint, flash, redirect, render_template, url_for
from flask_login import current_user, login_user

from app.auth.forms import SigninForm
from app.models import User

auth = Blueprint("auth", __name__, url_prefix="/auth")

@auth.route("/signin", methods=["GET", "POST"])
def signin():
    if current_user.is_authenticated:
        return redirect(url_for("main.home"))
    form = SigninForm()
    if form.validate_on_submit():
        user = User.authenticate(
            username=form.username.data, password=form.password.data
        )
        if user:
            login_user(user, remember=form.remember.data)
            flash(f"Hello, {form.username.data}", category="info")
            return redirect(url_for("main.home"))
        else:
            flash("Login Unsuccessful. Please check username and password", "danger")
    return render_template(
        "auth/signin.html", title="Sign in", icon="log-in", form=form
    )

EDIT:

My idea is to add the guest user manually to the DB even before the flask run. But what if the code is redistributed? I want to make the guest user creation to be automated using Python.

CodePudding user response:

You could try the before_first_request decorator. Docs: https://flask.palletsprojects.com/en/2.2.x/api/#flask.Flask.before_first_request

So something like this

from flask import Flask



app = Flask(__name__)


...


@app.before_first_request
def create_guest_user():
    # include code to create new user here
    pass
  • Related