Fix linting issues

This commit is contained in:
Adam Hopkins 2020-09-29 00:40:24 +03:00
parent 13094e02bc
commit 3483e7b061
8 changed files with 95 additions and 35 deletions

View File

@ -42,7 +42,7 @@ class BaseHTTPResponse:
body=b"",
):
""".. deprecated:: 20.3:
This function is not public API and will be removed."""
This function is not public API and will be removed."""
# self.headers get priority over content_type
if self.content_type and "Content-Type" not in self.headers:
@ -249,7 +249,10 @@ def raw(
:param content_type: the content type (string) of the response.
"""
return HTTPResponse(
body=body, status=status, headers=headers, content_type=content_type,
body=body,
status=status,
headers=headers,
content_type=content_type,
)

View File

@ -452,7 +452,7 @@ class Router:
return route_handler, [], kwargs, route.uri, route.name
def is_stream_handler(self, request):
""" Handler for request is stream or not.
"""Handler for request is stream or not.
:param request: Request object
:return: bool
"""

View File

@ -6,6 +6,7 @@ import socket
import stat
import sys
import traceback
from collections import deque
from functools import partial
from inspect import isawaitable
@ -32,6 +33,7 @@ from sanic.log import access_logger, logger
from sanic.request import EXPECT_HEADER, Request, StreamBuffer
from sanic.response import HTTPResponse
try:
import uvloop # type: ignore
@ -158,7 +160,9 @@ class HttpProtocol(asyncio.Protocol):
self.request_handler = self.app.handle_request
self.error_handler = self.app.error_handler
self.request_timeout = self.app.config.REQUEST_TIMEOUT
self.request_buffer_queue_size = self.app.config.REQUEST_BUFFER_QUEUE_SIZE
self.request_buffer_queue_size = (
self.app.config.REQUEST_BUFFER_QUEUE_SIZE
)
self.response_timeout = self.app.config.RESPONSE_TIMEOUT
self.keep_alive_timeout = self.app.config.KEEP_ALIVE_TIMEOUT
self.request_max_size = self.app.config.REQUEST_MAX_SIZE
@ -331,7 +335,9 @@ class HttpProtocol(asyncio.Protocol):
value = value.decode()
except UnicodeDecodeError:
value = value.decode("latin_1")
self.headers.append((self._header_fragment.decode().casefold(), value))
self.headers.append(
(self._header_fragment.decode().casefold(), value)
)
self._header_fragment = b""
@ -355,9 +361,13 @@ class HttpProtocol(asyncio.Protocol):
self.expect_handler()
if self.is_request_stream:
self._is_stream_handler = self.app.router.is_stream_handler(self.request)
self._is_stream_handler = self.app.router.is_stream_handler(
self.request
)
if self._is_stream_handler:
self.request.stream = StreamBuffer(self.request_buffer_queue_size)
self.request.stream = StreamBuffer(
self.request_buffer_queue_size
)
self.execute_request_handler()
def expect_handler(self):
@ -369,7 +379,9 @@ class HttpProtocol(asyncio.Protocol):
if expect.lower() == "100-continue":
self.transport.write(b"HTTP/1.1 100 Continue\r\n\r\n")
else:
self.write_error(HeaderExpectationFailed(f"Unknown Expect: {expect}"))
self.write_error(
HeaderExpectationFailed(f"Unknown Expect: {expect}")
)
def on_body(self, body):
if self.is_request_stream and self._is_stream_handler:
@ -378,8 +390,13 @@ class HttpProtocol(asyncio.Protocol):
# 3.7. so we should not create more than one task putting into the
# queue simultaneously.
self._body_chunks.append(body)
if not self._request_stream_task or self._request_stream_task.done():
self._request_stream_task = self.loop.create_task(self.stream_append())
if (
not self._request_stream_task
or self._request_stream_task.done()
):
self._request_stream_task = self.loop.create_task(
self.stream_append()
)
else:
self.request.body_push(body)
@ -416,8 +433,13 @@ class HttpProtocol(asyncio.Protocol):
self._request_timeout_handler = None
if self.is_request_stream and self._is_stream_handler:
self._body_chunks.append(None)
if not self._request_stream_task or self._request_stream_task.done():
self._request_stream_task = self.loop.create_task(self.stream_append())
if (
not self._request_stream_task
or self._request_stream_task.done()
):
self._request_stream_task = self.loop.create_task(
self.stream_append()
)
return
self.request.body_finish()
self.execute_request_handler()
@ -499,7 +521,8 @@ class HttpProtocol(asyncio.Protocol):
except RuntimeError:
if self.app.debug:
logger.error(
"Connection lost before response written @ %s", self.request.ip,
"Connection lost before response written @ %s",
self.request.ip,
)
keep_alive = False
except Exception as e:
@ -549,7 +572,8 @@ class HttpProtocol(asyncio.Protocol):
except RuntimeError:
if self.app.debug:
logger.error(
"Connection lost before response written @ %s", self.request.ip,
"Connection lost before response written @ %s",
self.request.ip,
)
keep_alive = False
except Exception as e:
@ -584,7 +608,8 @@ class HttpProtocol(asyncio.Protocol):
)
except Exception as e:
self.bail_out(
f"Writing error failed, connection closed {e!r}", from_error=True,
f"Writing error failed, connection closed {e!r}",
from_error=True,
)
finally:
if self.parser and (
@ -687,7 +712,13 @@ class AsyncioServer:
)
def __init__(
self, loop, serve_coro, connections, after_start, before_stop, after_stop,
self,
loop,
serve_coro,
connections,
after_start,
before_stop,
after_stop,
):
# Note, Sanic already called "before_server_start" events
# before this helper was even created. So we don't need it here.
@ -826,7 +857,9 @@ def serve(
unix=unix,
**protocol_kwargs,
)
asyncio_server_kwargs = asyncio_server_kwargs if asyncio_server_kwargs else {}
asyncio_server_kwargs = (
asyncio_server_kwargs if asyncio_server_kwargs else {}
)
# UNIX sockets are always bound by us (to preserve semantics between modes)
if unix:
sock = bind_unix_socket(unix, backlog=backlog)
@ -944,7 +977,9 @@ def bind_socket(host: str, port: int, *, backlog=100) -> socket.socket:
try: # IP address: family must be specified for IPv6 at least
ip = ip_address(host)
host = str(ip)
sock = socket.socket(socket.AF_INET6 if ip.version == 6 else socket.AF_INET)
sock = socket.socket(
socket.AF_INET6 if ip.version == 6 else socket.AF_INET
)
except ValueError: # Hostname, may become AF_INET or AF_INET6
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

View File

@ -103,7 +103,9 @@ class SanicTestClient:
if self.port:
server_kwargs = dict(
host=host or self.host, port=self.port, **server_kwargs,
host=host or self.host,
port=self.port,
**server_kwargs,
)
host, port = host or self.host, self.port
else:

View File

@ -174,7 +174,7 @@ class GunicornWorker(base.Worker):
@staticmethod
def _create_ssl_context(cfg):
""" Creates SSLContext instance for usage in asyncio.create_server.
"""Creates SSLContext instance for usage in asyncio.create_server.
See ssl.SSLSocket.__init__ for more details.
"""
ctx = ssl.SSLContext(cfg.ssl_version)

View File

@ -1,6 +1,7 @@
import asyncio
import logging
import sys
from inspect import isawaitable
from unittest.mock import patch
@ -30,7 +31,9 @@ def test_app_loop_running(app):
assert response.text == "pass"
@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires python3.7 or higher")
@pytest.mark.skipif(
sys.version_info < (3, 7), reason="requires python3.7 or higher"
)
def test_create_asyncio_server(app):
if not uvloop_installed():
loop = asyncio.get_event_loop()
@ -40,7 +43,9 @@ def test_create_asyncio_server(app):
assert srv.is_serving() is True
@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires python3.7 or higher")
@pytest.mark.skipif(
sys.version_info < (3, 7), reason="requires python3.7 or higher"
)
def test_asyncio_server_no_start_serving(app):
if not uvloop_installed():
loop = asyncio.get_event_loop()
@ -53,7 +58,9 @@ def test_asyncio_server_no_start_serving(app):
assert srv.is_serving() is False
@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires python3.7 or higher")
@pytest.mark.skipif(
sys.version_info < (3, 7), reason="requires python3.7 or higher"
)
def test_asyncio_server_start_serving(app):
if not uvloop_installed():
loop = asyncio.get_event_loop()
@ -166,9 +173,17 @@ def test_app_websocket_parameters(websocket_protocol_mock, app):
assert ws_kwargs["websocket_max_size"] == app.config.WEBSOCKET_MAX_SIZE
assert ws_kwargs["websocket_max_queue"] == app.config.WEBSOCKET_MAX_QUEUE
assert ws_kwargs["websocket_read_limit"] == app.config.WEBSOCKET_READ_LIMIT
assert ws_kwargs["websocket_write_limit"] == app.config.WEBSOCKET_WRITE_LIMIT
assert ws_kwargs["websocket_ping_timeout"] == app.config.WEBSOCKET_PING_TIMEOUT
assert ws_kwargs["websocket_ping_interval"] == app.config.WEBSOCKET_PING_INTERVAL
assert (
ws_kwargs["websocket_write_limit"] == app.config.WEBSOCKET_WRITE_LIMIT
)
assert (
ws_kwargs["websocket_ping_timeout"]
== app.config.WEBSOCKET_PING_TIMEOUT
)
assert (
ws_kwargs["websocket_ping_interval"]
== app.config.WEBSOCKET_PING_INTERVAL
)
def test_handle_request_with_nested_exception(app, monkeypatch):
@ -179,7 +194,9 @@ def test_handle_request_with_nested_exception(app, monkeypatch):
def mock_error_handler_response(*args, **kwargs):
raise Exception(err_msg)
monkeypatch.setattr(app.error_handler, "response", mock_error_handler_response)
monkeypatch.setattr(
app.error_handler, "response", mock_error_handler_response
)
@app.get("/")
def handler(request):
@ -198,7 +215,9 @@ def test_handle_request_with_nested_exception_debug(app, monkeypatch):
def mock_error_handler_response(*args, **kwargs):
raise Exception(err_msg)
monkeypatch.setattr(app.error_handler, "response", mock_error_handler_response)
monkeypatch.setattr(
app.error_handler, "response", mock_error_handler_response
)
@app.get("/")
def handler(request):
@ -217,7 +236,9 @@ def test_handle_request_with_nested_sanic_exception(app, monkeypatch, caplog):
def mock_error_handler_response(*args, **kwargs):
raise SanicException("Mock SanicException")
monkeypatch.setattr(app.error_handler, "response", mock_error_handler_response)
monkeypatch.setattr(
app.error_handler, "response", mock_error_handler_response
)
@app.get("/")
def handler(request):

View File

@ -244,8 +244,8 @@ async def handler3(request):
def test_keep_alive_timeout_reuse():
"""If the server keep-alive timeout and client keep-alive timeout are
both longer than the delay, the client _and_ server will successfully
reuse the existing connection."""
both longer than the delay, the client _and_ server will successfully
reuse the existing connection."""
try:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

View File

@ -46,8 +46,8 @@ def test_custom_context(app):
invalid = str(e)
j = loads(response.body)
j['response_mw_valid'] = user
j['response_mw_invalid'] = invalid
j["response_mw_valid"] = user
j["response_mw_invalid"] = invalid
return json(j)
request, response = app.test_client.get("/")
@ -59,8 +59,7 @@ def test_custom_context(app):
"has_missing": False,
"invalid": "'types.SimpleNamespace' object has no attribute 'missing'",
"response_mw_valid": "sanic",
"response_mw_invalid":
"'types.SimpleNamespace' object has no attribute 'missing'"
"response_mw_invalid": "'types.SimpleNamespace' object has no attribute 'missing'",
}