diff --git a/sanic/app.py b/sanic/app.py index d0ccc9e9..18913e09 100644 --- a/sanic/app.py +++ b/sanic/app.py @@ -988,14 +988,16 @@ class Sanic: # Define `response` var here to remove warnings about # allocation before assignment below. response = None - cancelled = False name = None try: # Fetch handler from router handler, args, kwargs, uri, name = self.router.get(request) # 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() # -------------------------------------------- # diff --git a/sanic/asgi.py b/sanic/asgi.py index 40cc5b05..3101a3de 100644 --- a/sanic/asgi.py +++ b/sanic/asgi.py @@ -21,7 +21,7 @@ from sanic.compat import Header from sanic.exceptions import InvalidUsage, ServerError from sanic.log import logger from sanic.request import Request -from sanic.response import HTTPResponse, StreamingHTTPResponse +from sanic.response import StreamingHTTPResponse from sanic.websocket import WebSocketConnection diff --git a/sanic/http.py b/sanic/http.py index ced93eff..c659c3ca 100644 --- a/sanic/http.py +++ b/sanic/http.py @@ -6,16 +6,12 @@ from sanic.exceptions import ( HeaderExpectationFailed, InvalidUsage, PayloadTooLarge, - RequestTimeout, - SanicException, ServerError, 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.log import access_logger, logger -from sanic.request import Request -from sanic.response import HTTPResponse class Stage(Enum): @@ -138,7 +134,7 @@ class Http: elif name == "connection": self.keep_alive = value.lower() == "keep-alive" headers.append(h) - except: + except Exception: raise InvalidUsage("Bad Request") # Prepare a Request object request = self.protocol.request_class( @@ -166,7 +162,9 @@ class Http: self.request_bytes_left = 0 pos -= 2 # One CRLF stays in buffer 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 del buf[: pos + 4] self.stage = Stage.HANDLER @@ -331,7 +329,7 @@ class Http: await self._receive_more() try: size = int(buf[2:pos].split(b";", 1)[0].decode(), 16) - except: + except Exception: self.keep_alive = False raise InvalidUsage("Bad chunked encoding") del buf[: pos + 2] @@ -344,7 +342,7 @@ class Http: self.request_bytes_left = size self.request_bytes += size # Request size limit - if (self.request_bytes > self.request_max_size): + if self.request_bytes > self.request_max_size: self.keep_alive = False raise PayloadTooLarge("Payload Too Large") # End of request body? diff --git a/sanic/request.py b/sanic/request.py index c77da108..29ad6f53 100644 --- a/sanic/request.py +++ b/sanic/request.py @@ -1,4 +1,3 @@ -import asyncio import email.utils import warnings @@ -9,7 +8,6 @@ from urllib.parse import parse_qs, parse_qsl, unquote, urlunparse from httptools import parse_url # type: ignore -from sanic.compat import Header from sanic.exceptions import InvalidUsage from sanic.headers import ( parse_content_header, diff --git a/sanic/response.py b/sanic/response.py index 53797699..355f885e 100644 --- a/sanic/response.py +++ b/sanic/response.py @@ -7,8 +7,8 @@ from urllib.parse import quote_plus from sanic.compat import Header, open_async from sanic.cookies import CookieJar -from sanic.headers import format_http1, format_http1_response -from sanic.helpers import has_message_body, remove_entity_headers +from sanic.headers import format_http1 +from sanic.helpers import has_message_body try: diff --git a/sanic/server.py b/sanic/server.py index 2393d089..d5977e6e 100644 --- a/sanic/server.py +++ b/sanic/server.py @@ -1,11 +1,8 @@ import asyncio -import enum import os import sys -import traceback from asyncio import CancelledError -from collections import deque from functools import partial from inspect import isawaitable from multiprocessing import Process @@ -13,18 +10,8 @@ from signal import SIG_IGN, SIGINT, SIGTERM, Signals from signal import signal as signal_func from socket import SO_REUSEADDR, SOL_SOCKET, socket from time import monotonic as current_time -from time import time -from sanic.compat import Header -from sanic.exceptions import ( - HeaderExpectationFailed, - InvalidUsage, - PayloadTooLarge, - RequestTimeout, - SanicException, - ServerError, - ServiceUnavailable, -) +from sanic.exceptions import RequestTimeout, ServiceUnavailable from sanic.http import Http, Stage from sanic.log import logger from sanic.request import Request @@ -147,14 +134,14 @@ class HttpProtocol(asyncio.Protocol): await self._http.http1() except CancelledError: pass - except: + except Exception: logger.exception("protocol.connection_task uncaught") finally: self._http = None self._task = None try: self.close() - except: + except BaseException: logger.exception("Closing failed") async def receive_more(self): @@ -191,7 +178,7 @@ class HttpProtocol(asyncio.Protocol): self.loop.call_later(max(0.1, interval), self.check_timeouts) return self._task.cancel() - except: + except Exception: logger.exception("protocol.check_timeouts") async def send(self, data): @@ -231,7 +218,7 @@ class HttpProtocol(asyncio.Protocol): self.transport = transport self._task = self.loop.create_task(self.connection_task()) self.recv_buffer = bytearray() - except: + except Exception: logger.exception("protocol.connect_made") def connection_lost(self, exc): @@ -240,11 +227,10 @@ class HttpProtocol(asyncio.Protocol): self.resume_writing() if self._task: self._task.cancel() - if self._debug and self._http and self._http.request: - logger.error( - f"Connection lost before response written @ {self._http.request.ip}", - ) - except: + if self._debug and self._http and self._http.response: + ip = self._http.request.ip + logger.error(f"Connection lost before response written @ {ip}") + except Exception: logger.exception("protocol.connection_lost") def pause_writing(self): @@ -266,7 +252,7 @@ class HttpProtocol(asyncio.Protocol): if self._data_received: self._data_received.set() - except: + except Exception: logger.exception("protocol.data_received") diff --git a/sanic/testing.py b/sanic/testing.py index 45c50d74..fbbd10b2 100644 --- a/sanic/testing.py +++ b/sanic/testing.py @@ -42,7 +42,7 @@ class SanicTestClient: ) except httpx.exceptions.ConnectionClosed: logger.error( - f"{method.upper()} {url} broken HTTP, response is None!" + f"{method.upper()} {url} received no response!" ) return None except NameError: