Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make login_required work with Fastapi routes #862

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

hmvp
Copy link

@hmvp hmvp commented Dec 10, 2024

Should fix #509

Kind of WIP. I could not get hatch to work locally and I am not entirely sure what kind of tests to add without implementing any form of app/route override

@hmvp
Copy link
Author

hmvp commented Dec 10, 2024

I needed this to use fastapi deps in custom views. The rest can be done with some creative code/monkeypatching

the other stuff needed is basically:

def init_admin(app: FastAPI, session_maker: async_sessionmaker) -> None:
    """Create the sqladmin class."""
    admin = Admin(
        app,
        session_maker=session_maker,
        base_url="/something_long_and_broken_so_we_don't_conflict",
        templates_dir=TEMPLATES_DIR,
    )

    # replace admin starlette app with fastapi so deps work
    admin.admin = FastAPI(
        routes=admin.admin.routes, exception_handlers=admin.admin.exception_handlers, debug=admin.admin.debug
    )

    # replace add_route with fastapi version
    def add_route(  # noqa: PLR0913
        self: FastAPI,
        path: str,
        route: typing.Callable[[Request], typing.Awaitable[Response] | Response],
        methods: list[str] | None = None,
        name: str | None = None,
        include_in_schema: bool = True,  # noqa: FBT001, FBT002
    ) -> None:
        self.add_api_route(path, endpoint=route, methods=methods, name=name, include_in_schema=include_in_schema)

    admin.admin.add_route = types.MethodType(add_route, admin.admin)

    # Mount admin on correct path
    app.mount("/admin", app=admin.admin, name="admin")

    admin.add_view(...)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add support custom routes
1 participant