from app import db from flask import flash, redirect, render_template, url_for from flask_bcrypt import generate_password_hash from flask_login import login_user from forms.registerform import RegisterForm from models.usermodel import User from sqlalchemy.exc import (DatabaseError, DataError, IntegrityError, InterfaceError, InvalidRequestError) from werkzeug.routing import BuildError 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)