Linter 'n fixes

This commit is contained in:
L. Kärkkäinen 2020-03-01 17:40:01 +02:00
parent 31a8706b42
commit 08353637fd
7 changed files with 25 additions and 41 deletions

View File

@ -988,14 +988,16 @@ 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 = None response = None
cancelled = False
name = None name = None
try: try:
# Fetch handler from router # Fetch handler from router
handler, args, kwargs, uri, name = self.router.get(request) handler, args, kwargs, uri, name = self.router.get(request)
# Non-streaming handlers have their body preloaded # Non-streaming handlers have their body preloaded
if request.stream.request_body and not self.router.is_stream_handler(request): if (
request.stream.request_body
and not self.router.is_stream_handler(request)
):
await request.receive_body() await request.receive_body()
# -------------------------------------------- # # -------------------------------------------- #

View File

@ -21,7 +21,7 @@ from sanic.compat import Header
from sanic.exceptions import InvalidUsage, ServerError from sanic.exceptions import InvalidUsage, ServerError
from sanic.log import logger from sanic.log import logger
from sanic.request import Request from sanic.request import Request
from sanic.response import HTTPResponse, StreamingHTTPResponse from sanic.response import StreamingHTTPResponse
from sanic.websocket import WebSocketConnection from sanic.websocket import WebSocketConnection

View File

@ -6,16 +6,12 @@ from sanic.exceptions import (
HeaderExpectationFailed, HeaderExpectationFailed,
InvalidUsage, InvalidUsage,
PayloadTooLarge, PayloadTooLarge,
RequestTimeout,
SanicException,
ServerError, ServerError,
ServiceUnavailable, ServiceUnavailable,
) )
from sanic.headers import format_http1, format_http1_response from sanic.headers import format_http1_response
from sanic.helpers import has_message_body, remove_entity_headers from sanic.helpers import has_message_body, remove_entity_headers
from sanic.log import access_logger, logger from sanic.log import access_logger, logger
from sanic.request import Request
from sanic.response import HTTPResponse
class Stage(Enum): class Stage(Enum):
@ -138,7 +134,7 @@ class Http:
elif name == "connection": elif name == "connection":
self.keep_alive = value.lower() == "keep-alive" self.keep_alive = value.lower() == "keep-alive"
headers.append(h) headers.append(h)
except: except Exception:
raise InvalidUsage("Bad Request") raise InvalidUsage("Bad Request")
# Prepare a Request object # Prepare a Request object
request = self.protocol.request_class( request = self.protocol.request_class(
@ -166,7 +162,9 @@ class Http:
self.request_bytes_left = 0 self.request_bytes_left = 0
pos -= 2 # One CRLF stays in buffer pos -= 2 # One CRLF stays in buffer
else: else:
self.request_bytes_left = self.request_bytes = int(headers["content-length"]) self.request_bytes_left = self.request_bytes = int(
headers["content-length"]
)
# Remove header and its trailing CRLF # Remove header and its trailing CRLF
del buf[: pos + 4] del buf[: pos + 4]
self.stage = Stage.HANDLER self.stage = Stage.HANDLER
@ -331,7 +329,7 @@ class Http:
await self._receive_more() await self._receive_more()
try: try:
size = int(buf[2:pos].split(b";", 1)[0].decode(), 16) size = int(buf[2:pos].split(b";", 1)[0].decode(), 16)
except: except Exception:
self.keep_alive = False self.keep_alive = False
raise InvalidUsage("Bad chunked encoding") raise InvalidUsage("Bad chunked encoding")
del buf[: pos + 2] del buf[: pos + 2]
@ -344,7 +342,7 @@ class Http:
self.request_bytes_left = size self.request_bytes_left = size
self.request_bytes += size self.request_bytes += size
# Request size limit # Request size limit
if (self.request_bytes > self.request_max_size): if self.request_bytes > self.request_max_size:
self.keep_alive = False self.keep_alive = False
raise PayloadTooLarge("Payload Too Large") raise PayloadTooLarge("Payload Too Large")
# End of request body? # End of request body?

View File

@ -1,4 +1,3 @@
import asyncio
import email.utils import email.utils
import warnings import warnings
@ -9,7 +8,6 @@ from urllib.parse import parse_qs, parse_qsl, unquote, urlunparse
from httptools import parse_url # type: ignore from httptools import parse_url # type: ignore
from sanic.compat import Header
from sanic.exceptions import InvalidUsage from sanic.exceptions import InvalidUsage
from sanic.headers import ( from sanic.headers import (
parse_content_header, parse_content_header,

View File

@ -7,8 +7,8 @@ from urllib.parse import quote_plus
from sanic.compat import Header, open_async from sanic.compat import Header, open_async
from sanic.cookies import CookieJar from sanic.cookies import CookieJar
from sanic.headers import format_http1, format_http1_response from sanic.headers import format_http1
from sanic.helpers import has_message_body, remove_entity_headers from sanic.helpers import has_message_body
try: try:

View File

@ -1,11 +1,8 @@
import asyncio import asyncio
import enum
import os import os
import sys import sys
import traceback
from asyncio import CancelledError from asyncio import CancelledError
from collections import deque
from functools import partial from functools import partial
from inspect import isawaitable from inspect import isawaitable
from multiprocessing import Process from multiprocessing import Process
@ -13,18 +10,8 @@ from signal import SIG_IGN, SIGINT, SIGTERM, Signals
from signal import signal as signal_func from signal import signal as signal_func
from socket import SO_REUSEADDR, SOL_SOCKET, socket from socket import SO_REUSEADDR, SOL_SOCKET, socket
from time import monotonic as current_time from time import monotonic as current_time
from time import time
from sanic.compat import Header from sanic.exceptions import RequestTimeout, ServiceUnavailable
from sanic.exceptions import (
HeaderExpectationFailed,
InvalidUsage,
PayloadTooLarge,
RequestTimeout,
SanicException,
ServerError,
ServiceUnavailable,
)
from sanic.http import Http, Stage from sanic.http import Http, Stage
from sanic.log import logger from sanic.log import logger
from sanic.request import Request from sanic.request import Request
@ -147,14 +134,14 @@ class HttpProtocol(asyncio.Protocol):
await self._http.http1() await self._http.http1()
except CancelledError: except CancelledError:
pass pass
except: except Exception:
logger.exception("protocol.connection_task uncaught") logger.exception("protocol.connection_task uncaught")
finally: finally:
self._http = None self._http = None
self._task = None self._task = None
try: try:
self.close() self.close()
except: except BaseException:
logger.exception("Closing failed") logger.exception("Closing failed")
async def receive_more(self): async def receive_more(self):
@ -191,7 +178,7 @@ class HttpProtocol(asyncio.Protocol):
self.loop.call_later(max(0.1, interval), self.check_timeouts) self.loop.call_later(max(0.1, interval), self.check_timeouts)
return return
self._task.cancel() self._task.cancel()
except: except Exception:
logger.exception("protocol.check_timeouts") logger.exception("protocol.check_timeouts")
async def send(self, data): async def send(self, data):
@ -231,7 +218,7 @@ class HttpProtocol(asyncio.Protocol):
self.transport = transport self.transport = transport
self._task = self.loop.create_task(self.connection_task()) self._task = self.loop.create_task(self.connection_task())
self.recv_buffer = bytearray() self.recv_buffer = bytearray()
except: except Exception:
logger.exception("protocol.connect_made") logger.exception("protocol.connect_made")
def connection_lost(self, exc): def connection_lost(self, exc):
@ -240,11 +227,10 @@ class HttpProtocol(asyncio.Protocol):
self.resume_writing() self.resume_writing()
if self._task: if self._task:
self._task.cancel() self._task.cancel()
if self._debug and self._http and self._http.request: if self._debug and self._http and self._http.response:
logger.error( ip = self._http.request.ip
f"Connection lost before response written @ {self._http.request.ip}", logger.error(f"Connection lost before response written @ {ip}")
) except Exception:
except:
logger.exception("protocol.connection_lost") logger.exception("protocol.connection_lost")
def pause_writing(self): def pause_writing(self):
@ -266,7 +252,7 @@ class HttpProtocol(asyncio.Protocol):
if self._data_received: if self._data_received:
self._data_received.set() self._data_received.set()
except: except Exception:
logger.exception("protocol.data_received") logger.exception("protocol.data_received")

View File

@ -42,7 +42,7 @@ class SanicTestClient:
) )
except httpx.exceptions.ConnectionClosed: except httpx.exceptions.ConnectionClosed:
logger.error( logger.error(
f"{method.upper()} {url} broken HTTP, response is None!" f"{method.upper()} {url} received no response!"
) )
return None return None
except NameError: except NameError: