from flask import Blueprint, flash, redirect, render_template, url_for from flask_bcrypt import generate_password_hash from flask_login import login_user from sqlalchemy.exc import ( DatabaseError, DataError, IntegrityError, InterfaceError, InvalidRequestError, ) from werkzeug.routing import BuildError from app import db from forms.registerform import RegisterForm from models.user_model import User register_user = Blueprint( "register", __name__, template_folder="templates/statuspengguna", static_folder="static", ) @register_user.route("/", methods=["GET", "POST"]) def register(): return RegisterUser() def RegisterUser(): registerform = RegisterForm() if registerform.validate_on_submit(): try: username = registerform.username.data email = registerform.email.data password = registerform.confirmpassword.data newuser = User( username=username, email=email, password=generate_password_hash(password), ) db.session.add(newuser) db.session.commit() flash("Account Succesfully created", "success") login_user(newuser) return redirect(url_for("index")) except InvalidRequestError: db.session.rollback() registerform.email.errors.append("Something went wrong!") flash("Something went wrong!", "danger") except IntegrityError: db.session.rollback() registerform.email.errors.append("User already exists!") flash("User already exists!", "warning") except DataError: db.session.rollback() registerform.email.errors.append("Invalid Entry") flash("Invalid Entry", "warning") except InterfaceError: db.session.rollback() registerform.email.errors.append( "Error connecting to the database" ) flash("Error connecting to the database", "danger") except DatabaseError: db.session.rollback() registerform.email.errors.append( "Error connecting to the database" ) flash("Error connecting to the database", "danger") except BuildError: db.session.rollback() registerform.email.errors.append("Unknown error occured!") flash("An error occured !", "danger") return render_template("register.html", registerform=registerform)