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 import asyncio
from sanic import Sanic from sanic import Sanic

View File

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

View File

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

View File

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

View File

@ -128,7 +128,7 @@ class Config(dict, metaclass=DescriptorMeta):
def __init__( def __init__(
self, 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, env_prefix: str | None = SANIC_PREFIX,
keep_alive: bool | None = None, keep_alive: bool | None = None,
*, *,

View File

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

View File

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

View File

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

View File

@ -401,9 +401,7 @@ class SessionTicketStore:
return self.tickets.pop(label, None) return self.tickets.pop(label, None)
def get_config( def get_config(app: Sanic, ssl: SanicSSLContext | CertSelector | SSLContext):
app: Sanic, ssl: SanicSSLContext | (CertSelector | SSLContext)
):
# TODO: # TODO:
# - proper selection needed if service with multiple certs insted of # - proper selection needed if service with multiple certs insted of
# just taking the first # 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}") raise ValueError(f"No certificate found matching hostname {server_name!r}")
def match_hostname( def match_hostname(ctx: ssl.SSLContext | CertSelector, hostname: str) -> bool:
ctx: ssl.SSLContext | CertSelector, hostname: str
) -> bool:
"""Match names from CertSelector against a received hostname.""" """Match names from CertSelector against a received hostname."""
# Local certs are considered trusted, so this can be less pedantic # Local certs are considered trusted, so this can be less pedantic
# and thus faster than the deprecated ssl.match_hostname function is. # 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 return path
def get_ssl_context( def get_ssl_context(app: Sanic, ssl: ssl.SSLContext | None) -> ssl.SSLContext:
app: Sanic, ssl: ssl.SSLContext | None
) -> ssl.SSLContext:
if ssl: if ssl:
return ssl return ssl

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1124,7 +1124,7 @@ def test_route_invalid_host(app):
return text("pass") return text("pass")
assert str(excinfo.value) == ( 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): def get(self, request):
self._iternal_method() self._iternal_method()
return text( return text(f"I am get method and global var is {self.global_var}")
f"I am get method and global var " f"is {self.global_var}"
)
app.add_route(DummyView.as_view(), "/") app.add_route(DummyView.as_view(), "/")
request, response = app.test_client.get("/") request, response = app.test_client.get("/")