HTTPMethod enum (#2165)

* Add HTTP enum constants

* Tests

* Add some more string compat
This commit is contained in:
Adam Hopkins 2021-06-16 15:13:55 +03:00 committed by GitHub
parent 48f8b37b74
commit d964b552af
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 56 additions and 2 deletions

View File

@ -1,2 +1,28 @@
HTTP_METHODS = ("GET", "POST", "PUT", "HEAD", "OPTIONS", "PATCH", "DELETE") from enum import Enum, auto
class HTTPMethod(str, Enum):
def _generate_next_value_(name, start, count, last_values):
return name.upper()
def __eq__(self, value: object) -> bool:
value = str(value).upper()
return super().__eq__(value)
def __hash__(self) -> int:
return hash(self.value)
def __str__(self) -> str:
return self.value
GET = auto()
POST = auto()
PUT = auto()
HEAD = auto()
OPTIONS = auto()
PATCH = auto()
DELETE = auto()
HTTP_METHODS = tuple(HTTPMethod.__members__.values())
DEFAULT_HTTP_CONTENT_TYPE = "application/octet-stream" DEFAULT_HTTP_CONTENT_TYPE = "application/octet-stream"

View File

@ -109,7 +109,7 @@ class Router(BaseRouter):
params = dict( params = dict(
path=uri, path=uri,
handler=handler, handler=handler,
methods=methods, methods=frozenset(map(str, methods)) if methods else None,
name=name, name=name,
strict=strict_slashes, strict=strict_slashes,
unquote=unquote, unquote=unquote,

28
tests/test_constants.py Normal file
View File

@ -0,0 +1,28 @@
from crypt import methods
from sanic import text
from sanic.constants import HTTP_METHODS, HTTPMethod
def test_string_compat():
assert "GET" == HTTPMethod.GET
assert "GET" in HTTP_METHODS
assert "get" == HTTPMethod.GET
assert "get" in HTTP_METHODS
assert HTTPMethod.GET.lower() == "get"
assert HTTPMethod.GET.upper() == "GET"
def test_use_in_routes(app):
@app.route("/", methods=[HTTPMethod.GET, HTTPMethod.POST])
def handler(_):
return text("It works")
_, response = app.test_client.get("/")
assert response.status == 200
assert response.text == "It works"
_, response = app.test_client.post("/")
assert response.status == 200
assert response.text == "It works"