diff --git a/examples/add_task_sanic.py b/examples/add_task_sanic.py index a4a07338..2ff86033 100644 --- a/examples/add_task_sanic.py +++ b/examples/add_task_sanic.py @@ -1,4 +1,3 @@ - import asyncio from sanic import Sanic diff --git a/examples/authorized_sanic.py b/examples/authorized_sanic.py index c3cd2cc5..9842f770 100644 --- a/examples/authorized_sanic.py +++ b/examples/authorized_sanic.py @@ -1,4 +1,3 @@ - from functools import wraps from sanic import Sanic diff --git a/pyproject.toml b/pyproject.toml index 27b5be80..03d69fa9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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 diff --git a/sanic/app.py b/sanic/app.py index 7314880e..30c9be8f 100644 --- a/sanic/app.py +++ b/sanic/app.py @@ -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 diff --git a/sanic/config.py b/sanic/config.py index 5d94e86f..df1eff34 100644 --- a/sanic/config.py +++ b/sanic/config.py @@ -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, *, diff --git a/sanic/exceptions.py b/sanic/exceptions.py index e515ee41..2076d6ea 100644 --- a/sanic/exceptions.py +++ b/sanic/exceptions.py @@ -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 = { diff --git a/sanic/handlers/content_range.py b/sanic/handlers/content_range.py index ba7b3197..998e90e1 100644 --- a/sanic/handlers/content_range.py +++ b/sanic/handlers/content_range.py @@ -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 diff --git a/sanic/handlers/error.py b/sanic/handlers/error.py index e023bc40..21c779b5 100644 --- a/sanic/handlers/error.py +++ b/sanic/handlers/error.py @@ -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) diff --git a/sanic/headers.py b/sanic/headers.py index 674a5f3e..8b618a4e 100644 --- a/sanic/headers.py +++ b/sanic/headers.py @@ -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) diff --git a/sanic/http/http3.py b/sanic/http/http3.py index fc9f8eba..9cca6250 100644 --- a/sanic/http/http3.py +++ b/sanic/http/http3.py @@ -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 diff --git a/sanic/http/tls/context.py b/sanic/http/tls/context.py index 35034863..7c03091f 100644 --- a/sanic/http/tls/context.py +++ b/sanic/http/tls/context.py @@ -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. diff --git a/sanic/http/tls/creators.py b/sanic/http/tls/creators.py index 9944a108..8ece9c54 100644 --- a/sanic/http/tls/creators.py +++ b/sanic/http/tls/creators.py @@ -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 diff --git a/sanic/log.py b/sanic/log.py index 066e9494..3bcc7cf6 100644 --- a/sanic/log.py +++ b/sanic/log.py @@ -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", }, diff --git a/sanic/models/protocol_types.py b/sanic/models/protocol_types.py index 2232ca43..f25737c9 100644 --- a/sanic/models/protocol_types.py +++ b/sanic/models/protocol_types.py @@ -19,6 +19,7 @@ class HTMLProtocol(Protocol): def _repr_html_(self) -> AnyStr: ... + class Range(Protocol): start: int | None end: int | None diff --git a/sanic/pages/directory_page.py b/sanic/pages/directory_page.py index 8d7d3b4e..f8431926 100644 --- a/sanic/pages/directory_page.py +++ b/sanic/pages/directory_page.py @@ -1,4 +1,3 @@ - from typing import Iterable, TypedDict from html5tagger import E diff --git a/sanic/request/parameters.py b/sanic/request/parameters.py index f28187e2..08940099 100644 --- a/sanic/request/parameters.py +++ b/sanic/request/parameters.py @@ -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: diff --git a/sanic/response/convenience.py b/sanic/response/convenience.py index a97d3efc..747093d4 100644 --- a/sanic/response/convenience.py +++ b/sanic/response/convenience.py @@ -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 diff --git a/sanic/server/protocols/websocket_protocol.py b/sanic/server/protocols/websocket_protocol.py index c1039c3c..475f7981 100644 --- a/sanic/server/protocols/websocket_protocol.py +++ b/sanic/server/protocols/websocket_protocol.py @@ -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, diff --git a/setup.py b/setup.py index bfa767b5..fb817e24 100644 --- a/setup.py +++ b/setup.py @@ -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 diff --git a/tests/test_response.py b/tests/test_response.py index d5257a75..1646cfe9 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -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 diff --git a/tests/test_routes.py b/tests/test_routes.py index a330f810..903fa55f 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -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}" ) diff --git a/tests/test_views.py b/tests/test_views.py index ab35679e..3c172786 100644 --- a/tests/test_views.py +++ b/tests/test_views.py @@ -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("/")