Search code examples
javascriptpythonflaskonbeforeunload

How to use the 'beforeunload' event method to route through Flask so a task gets executed in Python when a browser/tab is closed?


I have a perfectly functional website made using Flask/Python/SQLAlchemy, but after using it for a few minutes and closing the site, the attached Postgre database is left with the records I used during the just closed session, plus all the records stored from the previous sessions and those records have no further use and should be deleted.

app.py

@app.route('/db_cleanup')
def db_cleanup():
    db_table.query.filter_by(randomized = 100).delete()
return 'Database is clean.

The solution I have as of now is to manually delete the left over data to prevent the database to increase in size, before closing the website. As of now, I'm doing this through the code below.

index.html

<form action="/db_cleanup">
    <input type="submit" value="DB Cleaner" />
</form>

Now I'm working to implement this to automatically use the '@app.route('/db_cleanup') route using the 'beforeunload' event method but I can't make it to work, the code I'm using is:

index.html

<script>
    window.addEventListener('beforeunload', (event) => {
       console.log('Success!!');
       location.href = "/db_cleanup";
       for (var i = 0; i < 500000000; i++) { }
       event.preventDefault();
       event.returnValue = '';
    });
</script>

The 'beforeunload' event method is correctly triggered, and I can see the correct 'Success!!' message through the console, but somehow there is no routing to '/db_cleanup'.

Do anybody have any suggestion or solution?


Solution

  • Found the solution and it is working perfectly.

    I'm using an AJAX asynchronous call:

    index.html

    <script> 
        window.addEventListener('beforeunload', (event) => {
        clean_db()
        for (var i = 0; i < 500000000; i++) { };
        event.preventDefault();
        event.returnValue = '';
        });
    </script>
    

    script.js

    function clean_db() {
        var_url = "/db_cleanup";
        jQuery.ajax({
            url: var_url,
            success: function () {
               pass;
        }
    });
    return;
    

    }