I have an app running constantly (started in Linux with screen -S myapp python3 app.py
and then I detach it). It could be a Bottle app, Flask app, or any other system involving a forever-running event loop:
import anyframework # can be bottle, flask or anything else
import sqlite3
@route('/')
def index():
c = db.cursor()
c.execute('INSERT INTO test VALUES (?)', ('test',))
c.close() # we can't commit here for *each* client request, it would eat 100ms for each request
return 'hello'
@route('/makeitcrash')
def index():
sdlfksdfs # this will generate an error
def cleanup():
db.commit()
db = sqlite3.connect('test.db')
run()
How to make sure reliably that cleanup()
(and thus DB commit) is called in all possible cases of the server terminating? i.e.:
if the server is killed with SIGKILL, SIGTERM
if the server code has an error (exemple if http://example.com/makeitcrash is visited)
if I do CTRL+C in the terminal (inside the running
screen
)
?
I was about to use atexit
and to add try: except:
everywhere but I think it would introduce many code duplication to insert try: except:
for every route.
What is the general solution for this problem?