Skip to content

Class based view with inheritance #363

@Saurus119

Description

@Saurus119

Description
Hello, nice example of class based view. I was thinking also about the situation if I create a endpoint with the cbv decorator and I add inheritance to this class from the BaseController (my custom), where I want to specify all dependencies that are commonly used like: db_session, user from the JWT and so on. Will it work?

Example situation:

class BaseController:
    def __init__(self):
        self.db = Depends(get_db)
        self.user = Depends(get_jwt_user)

@cbv
class DemoController(BaseController):
    def __init__(self):
        super().__init__()
        self.specific_dependency = Depends(demo_controller_dependency)

    async def get_demo(self):
        print("Accessing BaseController")
        await self.db.query(DemoModel).all()
        print("Accessing DemoController namespace context")
        self.specific_dependency.do_something()

Would this implementation work without requiring any feature requests?
If not, I would be happy to look into it and create a merge request.

I see great potential in further reducing redundancy across CBV endpoints. With this approach, I would only need to inherit BaseController for each CBV route, instead of manually injecting the same dependencies repeatedly.

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions