Programmatically terminating/shutting-down Sanic as part of a request


I have the following code for Flask + Waitress + Webtest:

from flask import Flask
from webtest import http

app = Flask(__name__)

HOST = ""
PORT = 9000

@app.route("/shutdown", methods=["GET"])
def shutdown():
    return "Moo"

def main():
    global SERVER
    # this extends waitress
    SERVER = http.StopableWSGIServer(app, host=HOST, port=PORT, threads=THREADS)

if __name__ == "__main__":

The purpose of this code is when you request /shutdown, that the whole server shutsdown/terminates.

Is something like this possible with Sanic? If so, what is the most Sanoc-idiomatic way to achieve this?

The reason I’d like to move to Sanic (over Waitress) is the ability to use multiprocessing, so in terminating one worker, I’d like terminate the whole Sanic server (and therefore all other workers as well).

For some context: I’m very interested in using fast=True (but could also hard-code the number of workers) and I’d also like to be able to use this on Windows.



Oh, maybe I answered this myself:

from sanic import Sanic
from sanic.response import json

app = Sanic("my-hello-world-app")

async def test(request):
    global app
    return json({"hello": "world"})

if __name__ == "__main__":
    app.prepare(host="", port=1337, access_log=False, fast=True)

If there are suggestions for improvements, I’m all ears!


Two things…

  1. it is more idiomatic to use from inside the request handler.
  2. If you are using multiple workers (fast=True), I’d suggest using the multiplexer.

Ah, good to know about

For anyone else reading, here’s what my final version looked like:

from sanic import Sanic
from sanic.response import json

app = Sanic("my-hello-world-app")

async def test(request):
    return json({"hello": "world"})

if __name__ == "__main__":"", port=1337, access_log=False, fast=True)

Many thanks, @ahopkins!

@aytey It is also worth mentioning the inspector: Inspector | Sanic Framework

When you enable this, you get a background app that can provide insight and operational capacity to deal with your app. The benefit is that it decouples from your main app. By being on its own port you are not exposing sensitive endpoints.


I am new to sanic and a bit late to this discussion (nearly a year :sweat_smile:), but I have a related question: If the request leads to the server shutting down, then how will the response of the request be returned? Or does the app.m.terminate function just flag the server shutting down, and the shut down actually happens after that request has been served?


Sanic has a 15s graceful shutdown to handle terminating any in flight requests before fully shutting down.