Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

358
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda