Skip to content

Commit

Permalink
Replace % string formatting with f-string
Browse files Browse the repository at this point in the history
  • Loading branch information
dolfinus committed May 1, 2024
1 parent 0efd383 commit 647186f
Show file tree
Hide file tree
Showing 7 changed files with 18 additions and 15 deletions.
3 changes: 2 additions & 1 deletion tests/protocols/test_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -619,7 +619,8 @@ async def app(scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable
async def test_http10_request(http_protocol_cls: HTTPProtocol):
async def app(scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable):
assert scope["type"] == "http"
content = "Version: %s" % scope["http_version"]
version = scope["http_version"]
content = f"Version: {version}"
response = Response(content, media_type="text/plain")
await response(scope, receive, send)

Expand Down
2 changes: 1 addition & 1 deletion tests/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,5 @@ def set_content_type(self):
if self.media_type is not None and "content-type" not in self.headers:
content_type = self.media_type
if content_type.startswith("text/") and self.charset is not None:
content_type += "; charset=%s" % self.charset
content_type += f"; charset={self.charset}"
self.headers["content-type"] = content_type
2 changes: 1 addition & 1 deletion tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ def test_cli_incomplete_app_parameter() -> None:
result = runner.invoke(cli, ["tests.test_cli"])

assert (
'Error loading ASGI app. Import string "tests.test_cli" ' 'must be in format "<module>:<attribute>".'
'Error loading ASGI app: Import string "tests.test_cli" must be in format "<module>:<attribute>".'
) in result.output
assert result.exit_code == 1

Expand Down
2 changes: 1 addition & 1 deletion tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ def test_app_unimportable_other(caplog: pytest.LogCaptureFixture) -> None:
record.message for record in caplog.records if record.name == "uvicorn.error" and record.levelname == "ERROR"
]
assert (
'Error loading ASGI app. Attribute "app" not found in module "tests.test_config".' # noqa: E501
'Error loading ASGI app: Attribute "app" not found in module "tests.test_config".' # noqa: E501
== error_messages.pop(0)
)

Expand Down
6 changes: 3 additions & 3 deletions uvicorn/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -433,19 +433,19 @@ def load(self) -> None:
try:
self.loaded_app = import_from_string(self.app)
except ImportFromStringError as exc:
logger.error("Error loading ASGI app. %s" % exc)
logger.exception("Error loading ASGI app: %s", exc)
sys.exit(1)

try:
self.loaded_app = self.loaded_app()
except TypeError as exc:
if self.factory:
logger.error("Error loading ASGI app factory: %s", exc)
logger.exception("Error loading ASGI app factory: %s", exc)
sys.exit(1)
else:
if not self.factory:
logger.warning(
"ASGI app factory detected. Using it, " "but please consider setting the --factory flag explicitly."
"ASGI app factory detected. Using it, but please consider setting the --factory flag explicitly."
)

if self.interface == "auto":
Expand Down
12 changes: 6 additions & 6 deletions uvicorn/importer.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,23 @@ def import_from_string(import_str: Any) -> Any:

module_str, _, attrs_str = import_str.partition(":")
if not module_str or not attrs_str:
message = 'Import string "{import_str}" must be in format "<module>:<attribute>".'
raise ImportFromStringError(message.format(import_str=import_str))
message = f'Import string "{import_str}" must be in format "<module>:<attribute>".'
raise ImportFromStringError(message)

try:
module = importlib.import_module(module_str)
except ModuleNotFoundError as exc:
if exc.name != module_str:
raise exc from None
message = 'Could not import module "{module_str}".'
raise ImportFromStringError(message.format(module_str=module_str))
message = f'Could not import module "{module_str}".'
raise ImportFromStringError(message)

instance = module
try:
for attr_str in attrs_str.split("."):
instance = getattr(instance, attr_str)
except AttributeError:
message = 'Attribute "{attrs_str}" not found in module "{module_str}".'
raise ImportFromStringError(message.format(attrs_str=attrs_str, module_str=module_str))
message = f'Attribute "{attrs_str}" not found in module "{module_str}".'
raise ImportFromStringError(message)

return instance
6 changes: 4 additions & 2 deletions uvicorn/middleware/wsgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,13 @@ def build_environ(scope: HTTPScope, message: ASGIReceiveEvent, body: io.BytesIO)
path_info = scope["path"].encode("utf8").decode("latin1")
if path_info.startswith(script_name):
path_info = path_info[len(script_name) :]
version = scope["http_version"]
environ = {
"REQUEST_METHOD": scope["method"],
"SCRIPT_NAME": script_name,
"PATH_INFO": path_info,
"QUERY_STRING": scope["query_string"].decode("ascii"),
"SERVER_PROTOCOL": "HTTP/%s" % scope["http_version"],
"SERVER_PROTOCOL": f"HTTP/{version}",
"wsgi.version": (1, 0),
"wsgi.url_scheme": scope.get("scheme", "http"),
"wsgi.input": body,
Expand Down Expand Up @@ -67,7 +68,8 @@ def build_environ(scope: HTTPScope, message: ASGIReceiveEvent, body: io.BytesIO)
elif name_str == "content-type":
corrected_name = "CONTENT_TYPE"
else:
corrected_name = "HTTP_%s" % name_str.upper().replace("-", "_")
name_upper = name_str.upper().replace("-", "_")
corrected_name = f"HTTP_{name_upper}"
# HTTPbis say only ASCII chars are allowed in headers, but we latin1
# just in case
value_str: str = value.decode("latin1")
Expand Down

0 comments on commit 647186f

Please sign in to comment.