Skip to content

Commit

Permalink
Merge branch 'main' into missing-test-name
Browse files Browse the repository at this point in the history
  • Loading branch information
ahopkins committed Jun 23, 2024
2 parents 9335261 + b8cf4b2 commit eaba31d
Show file tree
Hide file tree
Showing 10 changed files with 40 additions and 71 deletions.
2 changes: 1 addition & 1 deletion sanic/blueprints.py
Original file line number Diff line number Diff line change
Expand Up @@ -391,7 +391,7 @@ def register(self, app, options):
name = future.name
if opt_name_prefix:
name = f"{opt_name_prefix}_{future.name}"
name = app._generate_name(name)
name = app.generate_name(name)
host = future.host or self.host
if isinstance(host, list):
host = tuple(host)
Expand Down
19 changes: 0 additions & 19 deletions sanic/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,25 +122,6 @@ def is_hop_by_hop_header(header):
return header.lower() in _HOP_BY_HOP_HEADERS


def remove_entity_headers(headers, allowed=("content-location", "expires")):
"""
Removes all the entity headers present in the headers given.
According to RFC 2616 Section 10.3.5,
Content-Location and Expires are allowed as for the
"strong cache validator".
https://tools.ietf.org/html/rfc2616#section-10.3.5
returns the headers without the entity headers
"""
allowed = set([h.lower() for h in allowed])
headers = {
header: value
for header, value in headers.items()
if not is_entity_header(header) or header.lower() in allowed
}
return headers


def import_string(module_name, package=None):
"""
import a module or class by string path.
Expand Down
49 changes: 28 additions & 21 deletions sanic/mixins/base.py
Original file line number Diff line number Diff line change
@@ -1,37 +1,44 @@
from typing import Optional
from typing import Optional, Protocol, Union

from sanic.base.meta import SanicMeta


class NameProtocol(Protocol):
name: str


class DunderNameProtocol(Protocol):
__name__: str


class BaseMixin(metaclass=SanicMeta):
"""Base class for some other mixins."""
"""Base class for various mixins."""

name: str
strict_slashes: Optional[bool]

def _generate_name(self, *objects) -> str:
name = None

def _generate_name(
self, *objects: Union[NameProtocol, DunderNameProtocol, str]
) -> str:
print(objects)
name: Optional[str] = None
for obj in objects:
if obj:
if isinstance(obj, str):
name = obj
break

try:
name = obj.name
except AttributeError:
try:
name = obj.__name__
except AttributeError:
continue
else:
break

if not name: # noqa
if not obj:
continue
if isinstance(obj, str):
name = obj
else:
name = getattr(obj, "name", getattr(obj, "__name__", None))

if name:
break
if not name or not isinstance(name, str):
raise ValueError("Could not generate a name for handler")

if not name.startswith(f"{self.name}."):
name = f"{self.name}.{name}"

return name

def generate_name(self, *objects) -> str:
return self._generate_name(*objects)
2 changes: 1 addition & 1 deletion sanic/mixins/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ def decorator(handler):
# variable will be a tuple of (existing routes, handler fn)
_, handler = handler

name = self._generate_name(name, handler)
name = self.generate_name(name, handler)

if isinstance(host, str):
host = frozenset([host])
Expand Down
2 changes: 1 addition & 1 deletion sanic/mixins/static.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ def static(
```
""" # noqa: E501

name = self._generate_name(name)
name = self.generate_name(name)

if strict_slashes is None and self.strict_slashes is not None:
strict_slashes = self.strict_slashes
Expand Down
4 changes: 0 additions & 4 deletions sanic/response/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
Default,
_default,
has_message_body,
remove_entity_headers,
)
from sanic.http import Http

Expand Down Expand Up @@ -104,9 +103,6 @@ def processed_headers(self) -> Iterator[Tuple[bytes, bytes]]:
Returns:
Iterator[Tuple[bytes, bytes]]: A list of header tuples encoded in bytes for sending
""" # noqa: E501
# TODO: Make a blacklist set of header names and then filter with that
if self.status in (304, 412): # Not Modified, Precondition Failed
self.headers = remove_entity_headers(self.headers)
if has_message_body(self.status):
self.headers.setdefault("content-type", self.content_type)
# Encode headers into bytes
Expand Down
2 changes: 1 addition & 1 deletion sanic/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ def find_route_by_view_name(

route = self.name_index.get(view_name)
if not route:
full_name = self.ctx.app._generate_name(view_name)
full_name = self.ctx.app.generate_name(view_name)
route = self.name_index.get(full_name)

if not route:
Expand Down
1 change: 0 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,6 @@ def str_to_bool(val: str) -> bool:
uvloop = "uvloop>=0.15.0" + env_dependency
types_ujson = "types-ujson" + env_dependency
requirements = [
# "sanic-routing>=23.6.0",
"sanic-routing>=23.12.0",
"httptools>=0.0.10",
uvloop,
Expand Down
22 changes: 0 additions & 22 deletions tests/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,28 +41,6 @@ def test_is_hop_by_hop_header():
assert helpers.is_hop_by_hop_header(header) is expected


def test_remove_entity_headers():
tests = (
({}, {}),
({"Allow": "GET, POST, HEAD"}, {}),
(
{
"Content-Type": "application/json",
"Expires": "Wed, 21 Oct 2015 07:28:00 GMT",
"Foo": "Bar",
},
{"Expires": "Wed, 21 Oct 2015 07:28:00 GMT", "Foo": "Bar"},
),
(
{"Allow": "GET, POST, HEAD", "Content-Location": "/test"},
{"Content-Location": "/test"},
),
)

for header, expected in tests:
assert helpers.remove_entity_headers(header) == expected


def test_import_string_class():
obj = helpers.import_string("sanic.config.Config")
assert isinstance(obj, Config)
Expand Down
8 changes: 8 additions & 0 deletions tests/test_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,10 @@ async def no_content_unmodified_handler(request: Request):
async def unmodified_handler(request: Request):
return json(JSON_DATA, status=304)

@app.get("/precondition")
async def precondition_handler(request: Request):
return json(JSON_DATA, status=412)

@app.delete("/")
async def delete_handler(request: Request):
return json(None, status=204)
Expand All @@ -193,6 +197,10 @@ def test_json_response(json_app):
assert response.text == json_dumps(JSON_DATA)
assert response.json == JSON_DATA

request, response = json_app.test_client.get("/precondition")
assert response.status == 412
assert response.json == JSON_DATA


def test_no_content(json_app):
request, response = json_app.test_client.get("/no-content")
Expand Down

0 comments on commit eaba31d

Please sign in to comment.