Skip to content

Commit 5547df9

Browse files
committed
Add example of graceful shutdown
1 parent 52738c7 commit 5547df9

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

Makefile

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,4 @@
11
run:
2-
gunicorn app:app -b 0.0.0.0:8080
2+
gunicorn app:app \
3+
--error-logfile - \
4+
-b 0.0.0.0:8080

app.py

+30-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,36 @@
1+
import signal, os, sys
2+
import time
13
from flask import Flask
24
app = Flask(__name__)
35

46
# Define route "/" named "index"
57
@app.route('/')
68
def index():
7-
return '🎉 Congratulations! Your first Python3 application is running on Stackhero!'
9+
return '🎉 Congratulations! Your first Python3 application is running on Stackhero!'
10+
11+
12+
# You'll see this log directly on your Stackhero's console
13+
print('🎉 The app has just start!')
14+
15+
16+
# Handle termination signal
17+
# When you will push your new code to Stackhero, we will send a termination signal (SIGTERM) to your running app.
18+
# The goal here is to let your app closing connections properly, like connections to databases etc...
19+
sigtermHandled = False
20+
def sigtermHandler(signum, frame):
21+
# Avoid to execute multiple time this function
22+
global sigtermHandled
23+
if sigtermHandled == True:
24+
return
25+
sigtermHandled = True
26+
27+
# You'll see this log directly on your Stackhero's console
28+
print('😯 SIGTERM signal received')
29+
30+
# You can close your database connection and do other cleanup here
31+
# dbConnection.close()
32+
33+
# Finally exit the process
34+
sys.exit(0)
35+
36+
signal.signal(signal.SIGTERM, sigtermHandler)

0 commit comments

Comments
 (0)