Skip to content
This repository was archived by the owner on Nov 10, 2024. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions fastapi_restful/cbv.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def new_init(self: Any, *args: Any, **kwargs: Any) -> None:


def _register_endpoints(router: APIRouter, cls: Type[Any], *urls: str) -> None:
cbv_router = APIRouter()
cbv_router = APIRouter(prefix=router.prefix)
function_members = inspect.getmembers(cls, inspect.isfunction)
for url in urls:
_allocate_routes_by_method_name(router, url, function_members)
Expand All @@ -112,7 +112,11 @@ def _register_endpoints(router: APIRouter, cls: Type[Any], *urls: str) -> None:
route.path = route.path[prefix_length:]
_update_cbv_route_endpoint_signature(cls, route)
cbv_router.routes.append(route)
router.include_router(cbv_router)
# Tempory remove prefix to by pass the prefix check and allow
# allow empty root method with a prefix
router.prefix = ""
router.include_router(cbv_router, prefix=cbv_router.prefix)
router.prefix = cbv_router.prefix


def _allocate_routes_by_method_name(router: APIRouter, url: str, function_members: List[Tuple[str, Any]]) -> None:
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -125,4 +125,4 @@ source = "init"

[build-system]
requires = ["poetry_core>=1.0.0"]
build-backend = "poetry.masonry.api"
build-backend = "poetry.core.masonry.api"
31 changes: 31 additions & 0 deletions tests/test_cbv.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from typing import Any, ClassVar

import pytest
from fastapi import APIRouter, Depends, FastAPI
from starlette.testclient import TestClient

Expand Down Expand Up @@ -97,3 +98,33 @@ def root(self) -> str:
response = client.get("/api/item")
assert response.status_code == 200
assert response.json() == "hello"


def test_prefix_and_empty_route() -> None:
router = APIRouter(prefix="/api")

@cbv(router)
class RootHandler:
@router.get("")
def root(self) -> str:
return "hello"

client = TestClient(router)
response = client.get("/api")
assert response.status_code == 200
assert response.json() == "hello"


def test_no_prefix_and_empty_route_raises() -> None:
router = APIRouter()

with pytest.raises(Exception):

@cbv(router)
class RootHandler:
@router.get("")
def root(self) -> str:
return "hello"

client = TestClient(router)
client.get("/api")