Home > OS >  Flask how to implement a User self-remove function
Flask how to implement a User self-remove function

Time:11-11

I'm writing a flask web app. User need to have a self-removal function. Basically to delete himself in the database. I have no idea how to implement this. I saw flask-security has delete_user. But don't know to to use it.

class User(UserMixin, db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, index=True)
    password_hash = db.Column(db.String(128))

That's my user model. UserMix is from flask-login Anyone can help out? Thanks

CodePudding user response:

You can make a function that accepts username in parameter

class User(UserMixin, db.Model):
    # Declarations here
    def delete(username):
        db.session.query(User).filter(User.username == username).delete()
        db.session.commit()

CodePudding user response:

I got it myself. Here is my solution:

In User model

def remove(self):
    db.session.delete(self)

In views

@main.route('/remove', methods=['GET', 'POST'])
@login_required
def remove():
    current_user.remove()
    db.session.commit()
    flash('You are no longer exist')
    return redirect(url_for('.index'))
  • Related