String literals and type annotations...

This commit is contained in:
L. Kärkkäinen 2023-10-25 02:59:41 +01:00
parent 65ba1942cc
commit 53b7412c01
22 changed files with 39 additions and 47 deletions

View File

@ -1,4 +1,3 @@
import asyncio
from sanic import Sanic

View File

@ -1,4 +1,3 @@
from functools import wraps
from sanic import Sanic

View File

@ -3,9 +3,21 @@ requires = ["setuptools", "wheel"]
build-backend = "setuptools.build_meta"
[tool.ruff]
extend-select = ["I", "W", "UP", "C4"]
# Worth selecting but still too broken: ASYNC, S, B
ignore = ["D100", "D101", "D102", "D103", "E402", "E741", "F811", "F821"]
extend-select = ["I", "W", "UP", "C4", "ISC"]
# Worth selecting but still too broken: ASYNC, S, B, DTZ, FA
ignore = [
"D100",
"D101",
"D102",
"D103",
"E402",
"E741",
"F811",
"F821",
# ruff format complains about these:
"ISC001",
"W191",
]
line-length = 79
show-source = true
show-fixes = true

View File

@ -1214,7 +1214,11 @@ class Sanic(
# Define `response` var here to remove warnings about
# allocation before assignment below.
response: BaseHTTPResponse | (Coroutine[Any, Any, BaseHTTPResponse | None] | ResponseStream) | None = None
response: (
BaseHTTPResponse
| (Coroutine[Any, Any, BaseHTTPResponse | None] | ResponseStream)
| None
) = None
run_middleware = True
try:
await self.dispatch(
@ -1272,10 +1276,8 @@ class Sanic(
if handler is None:
raise ServerError(
"'None' was returned while requesting a "
"handler from the router"
"'None' was returned while requesting a "
"handler from the router"
)
# Run response handler

View File

@ -128,7 +128,7 @@ class Config(dict, metaclass=DescriptorMeta):
def __init__(
self,
defaults: dict[str, str | (bool | (int | (float | None)))] | None = None,
defaults: dict[str, str | bool | int | float | None] | None = None,
env_prefix: str | None = SANIC_PREFIX,
keep_alive: bool | None = None,
*,

View File

@ -621,9 +621,7 @@ class Unauthorized(HTTPException):
# if auth-scheme is specified, set "WWW-Authenticate" header
if scheme is not None:
values = [
f'{k!s}="{v!s}"' for k, v in challenges.items()
]
values = [f'{k!s}="{v!s}"' for k, v in challenges.items()]
challenge = ", ".join(values)
self.headers = {

View File

@ -33,9 +33,7 @@ class ContentRangeHandler(Range):
raise HeaderNotFound("Range Header Not Found")
unit, _, value = tuple(map(str.strip, _range.partition("=")))
if unit != "bytes":
raise InvalidRangeType(
f"{unit} is not a valid Range Type", self
)
raise InvalidRangeType(f"{unit} is not a valid Range Type", self)
start_b, _, end_b = tuple(map(str.strip, value.partition("-")))
try:
self.start = int(start_b) if start_b else None

View File

@ -133,10 +133,8 @@ class ErrorHandler:
url = repr(request.url)
except AttributeError: # no cov
url = "unknown"
response_message = (
"Exception raised in exception handler " '"%s" for uri: %s'
)
error_logger.exception(response_message, handler.__name__, url)
response_message = f'Exception raised in exception handler "{handler.__name__}" for uri: {url}'
error_logger.exception(response_message)
if self.debug:
return text(response_message % (handler.__name__, url), 500)

View File

@ -153,7 +153,7 @@ class MediaType:
params = {
key.strip(): value.strip()
for key, value in (param.split("=", 1) for param in raw_params)
for key, value in (param.split("=", 1) for param in raw_params)
}
return cls(type_.lstrip(), subtype.rstrip(), **params)

View File

@ -401,9 +401,7 @@ class SessionTicketStore:
return self.tickets.pop(label, None)
def get_config(
app: Sanic, ssl: SanicSSLContext | (CertSelector | SSLContext)
):
def get_config(app: Sanic, ssl: SanicSSLContext | CertSelector | SSLContext):
# TODO:
# - proper selection needed if service with multiple certs insted of
# just taking the first

View File

@ -100,9 +100,7 @@ def find_cert(self: CertSelector, server_name: str):
raise ValueError(f"No certificate found matching hostname {server_name!r}")
def match_hostname(
ctx: ssl.SSLContext | CertSelector, hostname: str
) -> bool:
def match_hostname(ctx: ssl.SSLContext | CertSelector, hostname: str) -> bool:
"""Match names from CertSelector against a received hostname."""
# Local certs are considered trusted, so this can be less pedantic
# and thus faster than the deprecated ssl.match_hostname function is.

View File

@ -60,9 +60,7 @@ def _make_path(maybe_path: Path | str, tmpdir: Path | None) -> Path:
return path
def get_ssl_context(
app: Sanic, ssl: ssl.SSLContext | None
) -> ssl.SSLContext:
def get_ssl_context(app: Sanic, ssl: ssl.SSLContext | None) -> ssl.SSLContext:
if ssl:
return ssl

View File

@ -68,7 +68,7 @@ LOGGING_CONFIG_DEFAULTS: Dict[str, Any] = { # no cov
},
"access": {
"format": "%(asctime)s - (%(name)s)[%(levelname)s][%(host)s]: "
+ "%(request)s %(message)s %(status)s %(byte)s",
"%(request)s %(message)s %(status)s %(byte)s",
"datefmt": "[%Y-%m-%d %H:%M:%S %z]",
"class": "logging.Formatter",
},

View File

@ -19,6 +19,7 @@ class HTMLProtocol(Protocol):
def _repr_html_(self) -> AnyStr:
...
class Range(Protocol):
start: int | None
end: int | None

View File

@ -1,4 +1,3 @@
from typing import Iterable, TypedDict
from html5tagger import E

View File

@ -18,9 +18,7 @@ class RequestParameters(dict):
""" # noqa: E501
return super().get(name, [default])[0]
def getlist(
self, name: str, default: Any | None = None
) -> Any | None:
def getlist(self, name: str, default: Any | None = None) -> Any | None:
"""Return the entire list
Args:

View File

@ -170,7 +170,7 @@ async def validate_file(
if_modified_since = parsedate_to_datetime(if_modified_since)
except (TypeError, ValueError):
logger.warning(
"Ignorning invalid If-Modified-Since header received: " "'%s'",
"Ignoring invalid If-Modified-Since header received: '%s'",
if_modified_since,
)
return None

View File

@ -104,10 +104,7 @@ class WebSocketProtocol(HttpProtocol):
# but ServerProtocol needs a list
subprotocols = cast(
Optional[Sequence[Subprotocol]],
[
Subprotocol(subprotocol)
for subprotocol in subprotocols
],
[Subprotocol(subprotocol) for subprotocol in subprotocols],
)
ws_proto = ServerProtocol(
max_size=self.websocket_max_size,

View File

@ -97,7 +97,7 @@ setup_kwargs = {
}
env_dependency = (
'; sys_platform != "win32" ' 'and implementation_name == "cpython"'
'; sys_platform != "win32" and implementation_name == "cpython"'
)
ujson = "ujson>=1.35" + env_dependency
uvloop = "uvloop>=0.15.0" + env_dependency

View File

@ -641,7 +641,6 @@ def test_multiple_responses(
"been responded to."
)
with caplog.at_level(ERROR):
_, response = app.test_client.get("/1")
assert response.status == 200

View File

@ -1124,7 +1124,7 @@ def test_route_invalid_host(app):
return text("pass")
assert str(excinfo.value) == (
"Expected either string or Iterable of " f"host strings, not {host!r}"
f"Expected either string or Iterable of host strings, not {host!r}"
)

View File

@ -195,9 +195,7 @@ def test_with_custom_class_methods(app):
def get(self, request):
self._iternal_method()
return text(
f"I am get method and global var " f"is {self.global_var}"
)
return text(f"I am get method and global var is {self.global_var}")
app.add_route(DummyView.as_view(), "/")
request, response = app.test_client.get("/")