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

@ -249,7 +249,10 @@ def raw(
:param content_type: the content type (string) of the response. :param content_type: the content type (string) of the response.
""" """
return HTTPResponse( 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 return route_handler, [], kwargs, route.uri, route.name
def is_stream_handler(self, request): def is_stream_handler(self, request):
""" Handler for request is stream or not. """Handler for request is stream or not.
:param request: Request object :param request: Request object
:return: bool :return: bool
""" """

View File

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

View File

@ -103,7 +103,9 @@ class SanicTestClient:
if self.port: if self.port:
server_kwargs = dict( 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 host, port = host or self.host, self.port
else: else:

View File

@ -174,7 +174,7 @@ class GunicornWorker(base.Worker):
@staticmethod @staticmethod
def _create_ssl_context(cfg): 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. See ssl.SSLSocket.__init__ for more details.
""" """
ctx = ssl.SSLContext(cfg.ssl_version) ctx = ssl.SSLContext(cfg.ssl_version)

View File

@ -1,6 +1,7 @@
import asyncio import asyncio
import logging import logging
import sys import sys
from inspect import isawaitable from inspect import isawaitable
from unittest.mock import patch from unittest.mock import patch
@ -30,7 +31,9 @@ def test_app_loop_running(app):
assert response.text == "pass" 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): def test_create_asyncio_server(app):
if not uvloop_installed(): if not uvloop_installed():
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
@ -40,7 +43,9 @@ def test_create_asyncio_server(app):
assert srv.is_serving() is True 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): def test_asyncio_server_no_start_serving(app):
if not uvloop_installed(): if not uvloop_installed():
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
@ -53,7 +58,9 @@ def test_asyncio_server_no_start_serving(app):
assert srv.is_serving() is False 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): def test_asyncio_server_start_serving(app):
if not uvloop_installed(): if not uvloop_installed():
loop = asyncio.get_event_loop() 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_size"] == app.config.WEBSOCKET_MAX_SIZE
assert ws_kwargs["websocket_max_queue"] == app.config.WEBSOCKET_MAX_QUEUE 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_read_limit"] == app.config.WEBSOCKET_READ_LIMIT
assert ws_kwargs["websocket_write_limit"] == app.config.WEBSOCKET_WRITE_LIMIT assert (
assert ws_kwargs["websocket_ping_timeout"] == app.config.WEBSOCKET_PING_TIMEOUT ws_kwargs["websocket_write_limit"] == app.config.WEBSOCKET_WRITE_LIMIT
assert ws_kwargs["websocket_ping_interval"] == app.config.WEBSOCKET_PING_INTERVAL )
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): 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): def mock_error_handler_response(*args, **kwargs):
raise Exception(err_msg) 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("/") @app.get("/")
def handler(request): def handler(request):
@ -198,7 +215,9 @@ def test_handle_request_with_nested_exception_debug(app, monkeypatch):
def mock_error_handler_response(*args, **kwargs): def mock_error_handler_response(*args, **kwargs):
raise Exception(err_msg) 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("/") @app.get("/")
def handler(request): 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): def mock_error_handler_response(*args, **kwargs):
raise SanicException("Mock SanicException") 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("/") @app.get("/")
def handler(request): def handler(request):

View File

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