Ask coding questions

← Back to all posts
Run on Exit (Flask+Python)
h
BD103 (139)

Hi. I'm trying to create a Flask app that saves a dictionary variable to a .pkl file when the program is closed. I've tried two things...


The first that I tried was using the atexit module, like this.

from flask import Flask
import pickle
import atexit

app = Flask(__name__)
var = {
  "test": 1
}

def save_var():
  global var
  with open("var.pkl", "wb") as f:
    pickle.dump(var, f)

atexit.register(save_var)

# @app.route() handlers here

if __name__ == "__main__":
  app.run(host="0.0.0.0", port=8000)

This didn't work in the slightest, so next I tried running the command after app.run().

from flask import Flask
import pickle

app = Flask(__name__)
var = {
  "test": 1
}

def save_var():
  global var
  with open("var.pkl", "wb") as f:
    pickle.dump(var, f)

# @app.route handlers here

if __name__ == "__main__":
  app.run(host="0.0.0.0", port=8000)
  save_var()

This works if I press ctrl+c in the console, but not if I click the stop button.

Do you know what exactly the stop button does, and how I can clean up after it?

Thank you!