Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

364
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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;

}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!