Skip to content

Commit

Permalink
Merge branch 'main' into gh-2325
Browse files Browse the repository at this point in the history
  • Loading branch information
ahopkins committed Jun 15, 2022
2 parents d759831 + 49789b7 commit 539fcbe
Show file tree
Hide file tree
Showing 29 changed files with 254 additions and 111 deletions.
2 changes: 0 additions & 2 deletions .black.toml

This file was deleted.

6 changes: 3 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -66,15 +66,15 @@ ifdef include_tests
isort -rc sanic tests
else
$(info Sorting Imports)
isort -rc sanic tests --profile=black
isort -rc sanic tests
endif
endif

black:
black --config ./.black.toml sanic tests
black sanic tests

isort:
isort sanic tests --profile=black
isort sanic tests

pretty: black isort

Expand Down
2 changes: 1 addition & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ Hello World Example
from sanic import Sanic
from sanic.response import json
app = Sanic("My Hello, world app")
app = Sanic("my-hello-world-app")
@app.route('/')
async def test(request):
Expand Down
15 changes: 15 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,18 @@
[build-system]
requires = ["setuptools<60.0", "wheel"]
build-backend = "setuptools.build_meta"

[tool.black]
line-length = 79

[tool.isort]
atomic = true
default_section = "THIRDPARTY"
include_trailing_comma = true
known_first_party = "sanic"
known_third_party = "pytest"
line_length = 79
lines_after_imports = 2
lines_between_types = 1
multi_line_output = 3
profile = "black"
2 changes: 2 additions & 0 deletions sanic/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from sanic.constants import HTTPMethod
from sanic.request import Request
from sanic.response import HTTPResponse, html, json, text
from sanic.server.websockets.impl import WebsocketImplProtocol as Websocket


__all__ = (
Expand All @@ -13,6 +14,7 @@
"HTTPMethod",
"HTTPResponse",
"Request",
"Websocket",
"html",
"json",
"text",
Expand Down
2 changes: 1 addition & 1 deletion sanic/__version__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "22.3.1"
__version__ = "22.3.2"
8 changes: 4 additions & 4 deletions sanic/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
from sanic.compat import OS_IS_WINDOWS, enable_windows_color_support
from sanic.config import SANIC_PREFIX, Config
from sanic.exceptions import (
InvalidUsage,
BadRequest,
SanicException,
ServerError,
URLBuildError,
Expand Down Expand Up @@ -281,7 +281,7 @@ def register_listener(
valid = ", ".join(
map(lambda x: x.lower(), ListenerEvent.__members__.keys())
)
raise InvalidUsage(f"Invalid event: {event}. Use one of: {valid}")
raise BadRequest(f"Invalid event: {event}. Use one of: {valid}")

if "." in _event:
self.signal(_event.value)(
Expand Down Expand Up @@ -992,10 +992,10 @@ async def _websocket_handler(
cancelled = False
try:
await fut
except Exception as e:
self.error_handler.log(request, e)
except (CancelledError, ConnectionClosed):
cancelled = True
except Exception as e:
self.error_handler.log(request, e)
finally:
self.websocket_tasks.remove(fut)
if cancelled:
Expand Down
4 changes: 2 additions & 2 deletions sanic/errorpages.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from functools import partial
from traceback import extract_tb

from sanic.exceptions import InvalidUsage, SanicException
from sanic.exceptions import BadRequest, SanicException
from sanic.helpers import STATUS_CODES
from sanic.request import Request
from sanic.response import HTTPResponse, html, json, text
Expand Down Expand Up @@ -506,7 +506,7 @@ def exception_response(
# $ curl localhost:8000 -d '{"foo": "bar"}'
# And provide them with JSONRenderer
renderer = JSONRenderer if request.json else base
except InvalidUsage:
except BadRequest:
renderer = base
else:
renderer = RENDERERS_BY_CONFIG.get(render_format, renderer)
Expand Down
28 changes: 20 additions & 8 deletions sanic/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class NotFound(SanicException):
quiet = True


class InvalidUsage(SanicException):
class BadRequest(SanicException):
"""
**Status**: 400 Bad Request
"""
Expand All @@ -51,11 +51,14 @@ class InvalidUsage(SanicException):
quiet = True


class BadURL(InvalidUsage):
InvalidUsage = BadRequest


class BadURL(BadRequest):
...


class MethodNotSupported(SanicException):
class MethodNotAllowed(SanicException):
"""
**Status**: 405 Method Not Allowed
"""
Expand All @@ -68,6 +71,9 @@ def __init__(self, message, method, allowed_methods):
self.headers = {"Allow": ", ".join(allowed_methods)}


MethodNotSupported = MethodNotAllowed


class ServerError(SanicException):
"""
**Status**: 500 Internal Server Error
Expand Down Expand Up @@ -129,19 +135,19 @@ class PayloadTooLarge(SanicException):
quiet = True


class HeaderNotFound(InvalidUsage):
class HeaderNotFound(BadRequest):
"""
**Status**: 400 Bad Request
"""


class InvalidHeader(InvalidUsage):
class InvalidHeader(BadRequest):
"""
**Status**: 400 Bad Request
"""


class ContentRangeError(SanicException):
class RangeNotSatisfiable(SanicException):
"""
**Status**: 416 Range Not Satisfiable
"""
Expand All @@ -154,7 +160,10 @@ def __init__(self, message, content_range):
self.headers = {"Content-Range": f"bytes */{content_range.total}"}


class HeaderExpectationFailed(SanicException):
ContentRangeError = RangeNotSatisfiable


class ExpectationFailed(SanicException):
"""
**Status**: 417 Expectation Failed
"""
Expand All @@ -163,6 +172,9 @@ class HeaderExpectationFailed(SanicException):
quiet = True


HeaderExpectationFailed = ExpectationFailed


class Forbidden(SanicException):
"""
**Status**: 403 Forbidden
Expand All @@ -172,7 +184,7 @@ class Forbidden(SanicException):
quiet = True


class InvalidRangeType(ContentRangeError):
class InvalidRangeType(RangeNotSatisfiable):
"""
**Status**: 416 Range Not Satisfiable
"""
Expand Down
12 changes: 6 additions & 6 deletions sanic/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@
exception_response,
)
from sanic.exceptions import (
ContentRangeError,
HeaderNotFound,
InvalidRangeType,
RangeNotSatisfiable,
SanicException,
)
from sanic.helpers import Default, _default
Expand Down Expand Up @@ -78,7 +78,7 @@ def _warn_fallback_deprecation():
@classmethod
def _get_fallback_value(cls, error_handler: ErrorHandler, config: Config):
if error_handler._fallback is not _default:
if config._FALLBACK_ERROR_FORMAT is _default:
if config._FALLBACK_ERROR_FORMAT == error_handler._fallback:
return error_handler.fallback

error_logger.warning(
Expand Down Expand Up @@ -296,18 +296,18 @@ def __init__(self, request, stats):
try:
self.start = int(start_b) if start_b else None
except ValueError:
raise ContentRangeError(
raise RangeNotSatisfiable(
"'%s' is invalid for Content Range" % (start_b,), self
)
try:
self.end = int(end_b) if end_b else None
except ValueError:
raise ContentRangeError(
raise RangeNotSatisfiable(
"'%s' is invalid for Content Range" % (end_b,), self
)
if self.end is None:
if self.start is None:
raise ContentRangeError(
raise RangeNotSatisfiable(
"Invalid for Content Range parameters", self
)
else:
Expand All @@ -319,7 +319,7 @@ def __init__(self, request, stats):
self.start = self.total - self.end
self.end = self.total - 1
if self.start >= self.end:
raise ContentRangeError(
raise RangeNotSatisfiable(
"Invalid for Content Range parameters", self
)
self.size = self.end - self.start + 1
Expand Down
24 changes: 12 additions & 12 deletions sanic/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@

from sanic.compat import Header
from sanic.exceptions import (
HeaderExpectationFailed,
InvalidUsage,
BadRequest,
ExpectationFailed,
PayloadTooLarge,
ServerError,
ServiceUnavailable,
Expand Down Expand Up @@ -53,14 +53,14 @@ class Http(metaclass=TouchUpMeta):
:raises ServerError:
:raises PayloadTooLarge:
:raises Exception:
:raises InvalidUsage:
:raises HeaderExpectationFailed:
:raises BadRequest:
:raises ExpectationFailed:
:raises RuntimeError:
:raises ServerError:
:raises ServerError:
:raises InvalidUsage:
:raises InvalidUsage:
:raises InvalidUsage:
:raises BadRequest:
:raises BadRequest:
:raises BadRequest:
:raises PayloadTooLarge:
:raises RuntimeError:
"""
Expand Down Expand Up @@ -248,7 +248,7 @@ async def http1_request_header(self): # no cov

headers.append(h)
except Exception:
raise InvalidUsage("Bad Request")
raise BadRequest("Bad Request")

headers_instance = Header(headers)
self.upgrade_websocket = (
Expand Down Expand Up @@ -281,7 +281,7 @@ async def http1_request_header(self): # no cov
if expect.lower() == "100-continue":
self.expecting_continue = True
else:
raise HeaderExpectationFailed(f"Unknown Expect: {expect}")
raise ExpectationFailed(f"Unknown Expect: {expect}")

if headers.getone("transfer-encoding", None) == "chunked":
self.request_body = "chunked"
Expand Down Expand Up @@ -510,22 +510,22 @@ async def read(self) -> Optional[bytes]: # no cov

if len(buf) > 64:
self.keep_alive = False
raise InvalidUsage("Bad chunked encoding")
raise BadRequest("Bad chunked encoding")

await self._receive_more()

try:
size = int(buf[2:pos].split(b";", 1)[0].decode(), 16)
except Exception:
self.keep_alive = False
raise InvalidUsage("Bad chunked encoding")
raise BadRequest("Bad chunked encoding")

if size <= 0:
self.request_body = None

if size < 0:
self.keep_alive = False
raise InvalidUsage("Bad chunked encoding")
raise BadRequest("Bad chunked encoding")

# Consume CRLF, chunk size 0 and the two CRLF that follow
pos += 4
Expand Down
4 changes: 2 additions & 2 deletions sanic/mixins/listeners.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from typing import Callable, List, Optional, Union, overload

from sanic.base.meta import SanicMeta
from sanic.exceptions import InvalidUsage
from sanic.exceptions import BadRequest
from sanic.models.futures import FutureListener
from sanic.models.handler_types import ListenerType, Sanic

Expand Down Expand Up @@ -86,7 +86,7 @@ def register_listener(

if callable(listener_or_event):
if event_or_none is None:
raise InvalidUsage(
raise BadRequest(
"Invalid event registration: Missing event name."
)
return register_listener(listener_or_event, event_or_none)
Expand Down
8 changes: 4 additions & 4 deletions sanic/mixins/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@
from sanic.constants import DEFAULT_HTTP_CONTENT_TYPE, HTTP_METHODS
from sanic.errorpages import RESPONSE_MAPPING
from sanic.exceptions import (
ContentRangeError,
BadRequest,
FileNotFound,
HeaderNotFound,
InvalidUsage,
RangeNotSatisfiable,
)
from sanic.handlers import ContentRangeHandler
from sanic.log import deprecation, error_logger
Expand Down Expand Up @@ -778,7 +778,7 @@ async def _static_request_handler(
# Using this to determine if the URL is trying to break out of the path
# served. os.path.realpath seems to be very slow
if __file_uri__ and "../" in __file_uri__:
raise InvalidUsage("Invalid URL")
raise BadRequest("Invalid URL")
# Merge served directory and requested file if provided
# Strip all / that in the beginning of the URL to help prevent python
# from herping a derp and treating the uri as an absolute path
Expand Down Expand Up @@ -865,7 +865,7 @@ async def _static_request_handler(
file_path, headers=headers, _range=_range
)
return await file(file_path, headers=headers, _range=_range)
except ContentRangeError:
except RangeNotSatisfiable:
raise
except FileNotFoundError:
raise FileNotFound(
Expand Down
Loading

0 comments on commit 539fcbe

Please sign in to comment.