HTTPConnection 类¶
当您想定义应同时兼容 HTTP 和 WebSocket 的依赖项时,可以定义一个参数,该参数接受 HTTPConnection 而不是 Request 或 WebSocket。
你可以从 fastapi.requests 导入它
from fastapi.requests import HTTPConnection
fastapi.requests.HTTPConnection ¶
HTTPConnection(scope, receive=None)
基类: Mapping[str, Any], Generic[StateT]
用于传入 HTTP 连接的基类,用于提供 Request 和 WebSocket 共有的任何功能。
源代码在 starlette/requests.py
def __init__(self, scope: Scope, receive: Receive | None = None) -> None:
assert scope["type"] in ("http", "websocket")
self.scope = scope
url_for ¶
url_for(name, /, **path_params)
源代码在 starlette/requests.py
def url_for(self, name: str, /, **path_params: Any) -> URL:
url_path_provider: Router | Starlette | None = self.scope.get("router") or self.scope.get("app")
if url_path_provider is None:
raise RuntimeError("The `url_for` method can only be used inside a Starlette application or with a router.")
url_path = url_path_provider.url_path_for(name, **path_params)
return url_path.make_absolute_url(base_url=self.base_url)