MCPcopy Create free account
hub / github.com/encode/starlette / Host

Class Host

starlette/routing.py:468–531  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

466
467
468class Host(BaseRoute):
469 def __init__(self, host: str, app: ASGIApp, name: str | None = None) -> None:
470 assert not host.startswith("/"), "Host must not start with '/'"
471 self.host = host
472 self.app = app
473 self.name = name
474 self.host_regex, self.host_format, self.param_convertors = compile_path(host)
475
476 @property
477 def routes(self) -> list[BaseRoute]:
478 return getattr(self.app, "routes", [])
479
480 def matches(self, scope: Scope) -> tuple[Match, Scope]:
481 if scope["type"] in ("http", "websocket"): # pragma:no branch
482 headers = Headers(scope=scope)
483 parsed_host = parse_host_header(headers.get("host"))
484 if parsed_host is None:
485 return Match.NONE, {}
486 host = parsed_host.host
487
488 match = self.host_regex.match(host)
489 if match:
490 matched_params = match.groupdict()
491 for key, value in matched_params.items():
492 matched_params[key] = self.param_convertors[key].convert(value)
493 path_params = dict(scope.get("path_params", {}))
494 path_params.update(matched_params)
495 child_scope = {"path_params": path_params, "endpoint": self.app}
496 return Match.FULL, child_scope
497 return Match.NONE, {}
498
499 def url_path_for(self, name: str, /, **path_params: Any) -> URLPath:
500 if self.name is not None and name == self.name and "path" in path_params:
501 # 'name' matches "<mount_name>".
502 path = path_params.pop("path")
503 host, remaining_params = replace_params(self.host_format, self.param_convertors, path_params)
504 if not remaining_params:
505 return URLPath(path=path, host=host)
506 elif self.name is None or name.startswith(self.name + ":"):
507 if self.name is None:
508 # No mount name.
509 remaining_name = name
510 else:
511 # 'name' matches "<mount_name>:<child_name>".
512 remaining_name = name[len(self.name) + 1 :]
513 host, remaining_params = replace_params(self.host_format, self.param_convertors, path_params)
514 for route in self.routes or []:
515 try:
516 url = route.url_path_for(remaining_name, **remaining_params)
517 return URLPath(path=str(url), protocol=url.protocol, host=host)
518 except NoMatchFound:
519 pass
520 raise NoMatchFound(name, path_params)
521
522 async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:
523 await self.app(scope, receive, send)
524
525 def __eq__(self, other: Any) -> bool:

Callers 10

test_schemas.pyFile · 0.90
test_routesFunction · 0.90
test_routing.pyFile · 0.90
test_host_reprFunction · 0.90
test_host_named_reprFunction · 0.90
hostMethod · 0.85

Calls

no outgoing calls

Tested by 6

test_routesFunction · 0.72
test_host_reprFunction · 0.72
test_host_named_reprFunction · 0.72