0

I have created a child class and inherited FastAPI class. I want to define a function lifespan inside it. To implement lifespan I need to create constructor inside myFastAPI class. Below is sample code.

class myFastAPI(FastAPI):

    def __init__(self):
        self.lifespan = self.lifeSpan

    @asynccontextmanager
    def lifeSpan(self):
        print("Start before Application")
        notification = Notification()
        yield {'client': notification}
        app.state.client.close()

@app.get("/check")
async def index(placeHolder: str) -> str:
    message = "API is up and running"
    client = request.app.state.client
    //some operations
    return message

@app.post("/a/b/c")
async def index(request, data) -> str:
    client = request.app.state.client
    result = somefunc(data, client)
    return result

When I try to bring up the API, it is giving below error.

File "/sdfjjgjg/File1.py", line 89, in <module>
    @app.get("/check")
  File "/asjgjgj/python3.8/site-packages/fastapi/applications.py", line 469, in get
    return self.router.get(
AttributeError: 'myFastAPI' object has no attribute 'router'

Why above error is coming and how to fix it. Note: lifespan function I want inside myFastAPI class not outside as it is given in most of the document.

LOrD_ARaGOrN
  • 3,884
  • 3
  • 27
  • 49
  • 1
    I did not check fastapi constructor, if any. But if any, you may want to call super.__init__() (not sure of the syntax) – Itération 122442 May 25 '23 at 08:12
  • [How to create a subclass](https://stackoverflow.com/a/1608905/21169587), as @Itération122442 stated you likely need to call the superclass constructor. – Shorn May 25 '23 at 08:15
  • What's the reason why you need to inherit the application in the first place? What doesn't work when using the regular lifespan event support in FastAPI? https://fastapi.tiangolo.com/advanced/events/ – MatsLindh May 25 '23 at 08:35
  • There are reasons for it, as we need to customize as per our environment. – LOrD_ARaGOrN May 25 '23 at 15:00

1 Answers1

0

Need to call superclass constructor

class myFastAPI(FastAPI):

    def __init__(self):
        super().__init__()
        self.lifespan = self.mylifeSpan

    @asynccontextmanager
    def mylifeSpan(self):
        print("Start before Application")
        notification = Notification()
        yield {'client': notification}
        app.state.client.close()

@app.get("/check")
async def index(placeHolder: str) -> str:
    message = "API is up and running"
    client = request.app.state.client
    //some operations
    return message

@app.post("/a/b/c")
async def index(request, data) -> str:
    client = request.app.state.client
    result = somefunc(data, client)
    return result
LOrD_ARaGOrN
  • 3,884
  • 3
  • 27
  • 49