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