This commit is contained in:
Adam Hopkins 2021-02-15 10:47:16 +02:00
parent b89f9a57e0
commit e91b3d40a2
7 changed files with 11 additions and 40 deletions

View File

@ -14,6 +14,7 @@ from traceback import format_exc
from typing import Any, Dict, Iterable, List, Optional, Set, Type, Union from typing import Any, Dict, Iterable, List, Optional, Set, Type, Union
from urllib.parse import urlencode, urlunparse from urllib.parse import urlencode, urlunparse
from sanic_routing.exceptions import FinalizationError
from sanic_routing.route import Route from sanic_routing.route import Route
from sanic import reloader_helpers from sanic import reloader_helpers
@ -24,8 +25,6 @@ from sanic.blueprints import Blueprint
from sanic.config import BASE_LOGO, Config from sanic.config import BASE_LOGO, Config
from sanic.exceptions import ( from sanic.exceptions import (
InvalidUsage, InvalidUsage,
MethodNotSupported,
NotFound,
SanicException, SanicException,
ServerError, ServerError,
URLBuildError, URLBuildError,
@ -226,8 +225,6 @@ class Sanic(BaseSanic):
return self.register_listener(listener.listener, listener.event) return self.register_listener(listener.listener, listener.event)
def _apply_route(self, route: FutureRoute) -> Route: def _apply_route(self, route: FutureRoute) -> Route:
# TODO:
# - move websocket handler out and attach it when applying
params = route._asdict() params = route._asdict()
websocket = params.pop("websocket", False) websocket = params.pop("websocket", False)
subprotocols = params.pop("subprotocols", None) subprotocols = params.pop("subprotocols", None)
@ -239,10 +236,8 @@ class Sanic(BaseSanic):
route.handler, route.handler,
subprotocols=subprotocols, subprotocols=subprotocols,
) )
websocket_handler.__name__ = ( websocket_handler.__name__ = route.handler.__name__ # type: ignore
"websocket_handler_" + route.handler.__name__ websocket_handler.is_websocket = True # type: ignore
)
websocket_handler.is_websocket = True
params["handler"] = websocket_handler params["handler"] = websocket_handler
return self.router.add(**params) return self.router.add(**params)
@ -304,7 +299,7 @@ class Sanic(BaseSanic):
blueprint.register(self, options) blueprint.register(self, options)
def url_for(self, view_name: str, **kwargs): def url_for(self, view_name: str, **kwargs):
r"""Build a URL based on a view name and the values provided. """Build a URL based on a view name and the values provided.
In order to build a URL, all request parameters must be supplied as In order to build a URL, all request parameters must be supplied as
keyword arguments, and each parameter must pass the test for the keyword arguments, and each parameter must pass the test for the
@ -315,7 +310,7 @@ class Sanic(BaseSanic):
the output URL's query string. the output URL's query string.
:param view_name: string referencing the view name :param view_name: string referencing the view name
:param \**kwargs: keys and values that are used to build request :param **kwargs: keys and values that are used to build request
parameters and query string arguments. parameters and query string arguments.
:return: the built URL :return: the built URL
@ -519,11 +514,9 @@ class Sanic(BaseSanic):
# Fetch handler from router # Fetch handler from router
( (
handler, handler,
args,
kwargs, kwargs,
uri, uri,
name, name,
endpoint,
ignore_body, ignore_body,
) = self.router.get(request) ) = self.router.get(request)
request.name = name request.name = name
@ -560,7 +553,7 @@ class Sanic(BaseSanic):
request.endpoint = request.name request.endpoint = request.name
# Run response handler # Run response handler
response = handler(request, *args, **kwargs) response = handler(request, **kwargs)
if isawaitable(response): if isawaitable(response):
response = await response response = await response
if response: if response:
@ -920,11 +913,9 @@ class Sanic(BaseSanic):
): ):
"""Helper function used by `run` and `create_server`.""" """Helper function used by `run` and `create_server`."""
# TODO:
# - Catch proper exception
try: try:
self.router.finalize() self.router.finalize()
except Exception as e: except FinalizationError as e:
if not Sanic.test_mode: if not Sanic.test_mode:
raise e raise e

View File

@ -1,5 +1,3 @@
from enum import Enum, auto
from functools import partial
from typing import Set from typing import Set
from sanic.models.futures import FutureException from sanic.models.futures import FutureException

View File

@ -1,4 +1,3 @@
from functools import partial
from inspect import signature from inspect import signature
from pathlib import PurePath from pathlib import PurePath
from typing import Set, Union from typing import Set, Union

View File

@ -1,5 +1,5 @@
from functools import lru_cache from functools import lru_cache
from typing import FrozenSet, Iterable, List, Optional, Union from typing import Iterable, List, Optional, Union
from sanic_routing import BaseRouter from sanic_routing import BaseRouter
from sanic_routing.exceptions import NoMethod from sanic_routing.exceptions import NoMethod
@ -44,17 +44,11 @@ class Router(BaseRouter):
allowed_methods=e.allowed_methods, allowed_methods=e.allowed_methods,
) )
# TODO: Implement response
# - args,
# - endpoint,
return ( return (
handler, handler,
(),
params, params,
route.path, route.path,
route.name, route.name,
None,
route.ctx.ignore_body, route.ctx.ignore_body,
) )
@ -79,7 +73,7 @@ class Router(BaseRouter):
uri: str, uri: str,
methods: Iterable[str], methods: Iterable[str],
handler, handler,
host: Optional[Union[str, FrozenSet[str]]] = None, host: Optional[Union[str, Iterable[str]]] = None,
strict_slashes: bool = False, strict_slashes: bool = False,
stream: bool = False, stream: bool = False,
ignore_body: bool = False, ignore_body: bool = False,
@ -115,11 +109,6 @@ class Router(BaseRouter):
:return: the route object :return: the route object
:rtype: Route :rtype: Route
""" """
# TODO: Implement
# - host
# - strict_slashes
# - ignore_body
# - stream
if version is not None: if version is not None:
version = str(version).strip("/").lstrip("v") version = str(version).strip("/").lstrip("v")
uri = "/".join([f"/v{version}", uri.lstrip("/")]) uri = "/".join([f"/v{version}", uri.lstrip("/")])
@ -136,7 +125,7 @@ class Router(BaseRouter):
if isinstance(host, str): if isinstance(host, str):
hosts = [host] hosts = [host]
else: else:
hosts = host or [None] hosts = host or [None] # type: ignore
routes = [] routes = []
@ -185,10 +174,6 @@ class Router(BaseRouter):
if not view_name: if not view_name:
return None return None
# TODO:
# - Check blueprint naming, we shouldn't need to double check here
# but it seems like blueprints are not receiving full names
# probably need tocheck the blueprint registration func
route = self.name_index.get(view_name) route = self.name_index.get(view_name)
if not route: if not route:
full_name = self.ctx.app._generate_name(view_name) full_name = self.ctx.app._generate_name(view_name)

View File

@ -5,7 +5,6 @@ import secrets
import socket import socket
import stat import stat
import sys import sys
import time
from asyncio import CancelledError from asyncio import CancelledError
from functools import partial from functools import partial

View File

@ -6,8 +6,6 @@ from re import sub
from time import gmtime, strftime from time import gmtime, strftime
from urllib.parse import unquote from urllib.parse import unquote
from sanic_routing.patterns import REGEX_TYPES
from sanic.compat import stat_async from sanic.compat import stat_async
from sanic.exceptions import ( from sanic.exceptions import (
ContentRangeError, ContentRangeError,

View File

@ -83,6 +83,7 @@ ujson = "ujson>=1.35" + env_dependency
uvloop = "uvloop>=0.5.3" + env_dependency uvloop = "uvloop>=0.5.3" + env_dependency
requirements = [ requirements = [
"sanic-routing",
"httptools>=0.0.10", "httptools>=0.0.10",
uvloop, uvloop,
ujson, ujson,