Search code examples
pythonsqliteflasksqlalchemyapscheduler

Schedule SQLAlchemy to clear all rows from a table


I'm trying to create a function that can be scheduled to delete all rows within an SQLAlchemy model.

I'm trying to use apscheduler to accomplish this task. But I keep getting an error that says:

sqlalchemy.orm.exc.UnmappedInstanceError: Class 'flask_sqlalchemy.model.DefaultMeta' is not mapped; was a class (app.models.User) supplied where an instance was required?

Am I missing something?

Here is my app/__init__.py:

from flask import Flask
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
from config import Config

app = Flask(__name__)

db = SQLAlchemy()
login = LoginManager()

app.config.from_object(Config)
db.init_app(app)
login.init_app(app)
login.login_view = 'login'

from app import routes, models

and here is my manage.py:

from apscheduler.schedulers.background import BackgroundScheduler
from app import app, db
from flask_migrate import Migrate
from flask_script import Manager
from app.models import User

manager = Manager(app)

migrate = Migrate(app, db)

def clear_data():
    db.session.delete(User)
    print("Deleted User table!")

@manager.command
def run():
    scheduler = BackgroundScheduler()
    scheduler.add_job(clear_data, trigger='interval', seconds=5)
    scheduler.start()
    app.run(debug=True)

if __name__ == '__main__':
    manager.run()

Also, here's my model:

from app import db, login
from datetime import datetime
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True, unique=True)
    api_token = db.Column(db.String(50), unique=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password_hash = db.Column(db.String(128))
    todos = db.relationship('Todo', backref='owner', lazy='dynamic')

    def __repr__(self):
        return '<models.py {}>'.format(self.username)

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)


@login.user_loader
def load_user(id):
    return User.query.get(int(id))


class Todo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    body = db.Column(db.String(140))
    timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

    def __repr__(self):
        return '<Todo {}>'.format(self.body)

Solution

  • As your error indicated, it is expecting an instances of an object, and you instead passed it a class. I think the issue is the first line in the clear_data function:

    db.session.delete(User)
    

    It was expecting an instances of a User record to delete, and doesn't know how to delete the whole table using just the model.

    Check out this answer on how to delete all rows in a table. There are a few ways to do this, but this may be the least change for you:

    db.session.query(User).delete()
    

    In this case you are adding the step of SELECTing all the records in the table User maps to, then deleting them.

    P.S.: as mentioned in the linked answer, you need to .commit() your session, otherwise it won't stick, and will rollback after you close the connection.

    db.session.commit()