Skip to content

Why on_event('shutdown') in function not work #4860

@dongfengweixiao

Description

@dongfengweixiao

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from fastapi import FastAPI

def register_init(app: FastAPI) -> None:
    @app.on_event("startup")
    async def init_connect():
        print("init_connect...")

    @app.on_event('shutdown')
    async def shutdown_connect():
        print("shutdown_connect...")


def create_app() -> FastAPI:
    app = FastAPI()
    
    register_init(app) # comment this line and uncomment code block blow
    
    return app


app = create_app()


# @app.on_event("startup")
# async def init_connect():
#     print("init_connect...")


# @app.on_event('shutdown')
# async def shutdown_connect():
#     print("shutdown_connect...")


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app='main:app', host="127.0.0.1", port=8010, reload=True, debug=True)

Description

Default code only print "init_connect"

uncomment can print "init_connect" and "shutdown_connect".

Operating System

Windows

Operating System Details

No response

FastAPI Version

0.75.2

Python Version

Python 3.10.4

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions