In Docker, I run uvicorn with bootstrap.sh & command line. In code there is a condition about public key file, if exception occurs, server needs to shutdown.
So what I want to do in main.py is here (It is FastAPI).
public_key = None
try:
with open(PUBLIC_KEY_FILE) as public_key_file:
public_key = public_key_file.read()
except Exception as f_error:
logger.exception(f_error)
module = util.find_spec("uvicorn")
if module:
uvicorn = import_module('uvicorn')
uvicorn.stop() # what I want to do
However, I couldn't find a way to shutdown uvicorn server programmatically. What would be the best approach?
Raising an exception (or re-raising f_error) inside your except clause would terminate the current application unless there's another level of exception handling outside of the code you've included.
When the python interpreter receives a top level exception (i.e. one that isn't caught by except
), the interpreter terminates. You can use this to shut down your script and trigger your container runtime to restart the application as necessary.