]> git.ipfire.org Git - thirdparty/starlette.git/commitdiff
perf: avoid regex re-compile (#2700)
authorTrim21 <trim21.me@gmail.com>
Mon, 23 Sep 2024 06:54:17 +0000 (14:54 +0800)
committerGitHub <noreply@github.com>
Mon, 23 Sep 2024 06:54:17 +0000 (08:54 +0200)
* perf

* format

* avoid

* fix

starlette/responses.py
starlette/schemas.py

index b73e04a40765692ac693a66b542e199ec93d1f8e..fc92cbab136230184d0a096c318c639741edad79 100644 (file)
@@ -272,6 +272,9 @@ class RangeNotSatisfiable(Exception):
         self.max_size = max_size
 
 
+_RANGE_PATTERN = re.compile(r"(\d*)-(\d*)")
+
+
 class FileResponse(Response):
     chunk_size = 64 * 1024
 
@@ -453,7 +456,7 @@ class FileResponse(Response):
                 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 _ != ("", "")
         ]
 
index 688fd85bed2d25d56c0b98fa89f2d03cd05f46fe..94b9cca78307818149a12b440d8fb88756ee666b 100644 (file)
@@ -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
@@ -89,7 +92,7 @@ class BaseSchemaGenerator:
             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]:
         """