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

perf: avoid regex re-compile #2700

Merged
merged 4 commits into from
Sep 23, 2024
Merged
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
5 changes: 4 additions & 1 deletion starlette/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,9 @@ def __init__(self, max_size: int) -> None:
self.max_size = max_size


_RANGE_PATTERN = re.compile(r"(\d*)-(\d*)")


class FileResponse(Response):
chunk_size = 64 * 1024

Expand Down Expand Up @@ -453,7 +456,7 @@ def _parse_range_header(http_range: str, file_size: int) -> list[tuple[int, int]
int(_[0]) if _[0] else file_size - int(_[1]),
int(_[1]) + 1 if _[0] and _[1] and int(_[1]) < file_size else file_size,
)
for _ in re.findall(r"(\d*)-(\d*)", range_)
for _ in _RANGE_PATTERN.findall(range_)
if _ != ("", "")
]

Expand Down
5 changes: 4 additions & 1 deletion starlette/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ class EndpointInfo(typing.NamedTuple):
func: typing.Callable[..., typing.Any]


_remove_converter_pattern = re.compile(r":\w+}")


class BaseSchemaGenerator:
def get_schema(self, routes: list[BaseRoute]) -> dict[str, typing.Any]:
raise NotImplementedError() # pragma: no cover
Expand Down Expand Up @@ -89,7 +92,7 @@ def _remove_converter(self, path: str) -> str:
Route("/users/{id:int}", endpoint=get_user, methods=["GET"])
Should be represented as `/users/{id}` in the OpenAPI schema.
"""
return re.sub(r":\w+}", "}", path)
return _remove_converter_pattern.sub("}", path)

def parse_docstring(self, func_or_method: typing.Callable[..., typing.Any]) -> dict[str, typing.Any]:
"""
Expand Down