Skip to content

Instantly share code, notes, and snippets.

@devxpy
Last active August 9, 2020 23:43
Show Gist options
  • Save devxpy/e4b6faace73eec6d08a7dfe57ac486a1 to your computer and use it in GitHub Desktop.
Save devxpy/e4b6faace73eec6d08a7dfe57ac486a1 to your computer and use it in GitHub Desktop.
Script to run startlette & uvicorn in a way that forcefully exits/kills all pending background tasks automatically. A must have for development!
"""
Tired of seeing this annoying message - "Waiting for background tasks to complete."?
This hack can take care of that for you!
Usage -
$ python main.py
Bonus - easy to attach a debugger now
$ python -m pdb main.py
Github issue - https://github.com/encode/uvicorn/issues/675
"""
from starlette.applications import Starlette
app = Starlette(debug=True)
# your code goes here
if __name__ == "__main__":
from uvicorn.supervisors import ChangeReload
import uvicorn
config = uvicorn.Config("main:app", debug=app.debug, host="0.0.0.0")
server = uvicorn.Server(config=config)
server.force_exit = True
sock = config.bind_socket()
supervisor = ChangeReload(config, target=server.run, sockets=[sock])
supervisor.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment