Request
类
您可以在路径操作函数或依赖项中声明一个参数为 Request
类型,然后您可以直接访问原始请求对象,而无需任何验证等。
您可以直接从 fastapi
中导入它。
from fastapi import Request
提示
当您想要定义与 HTTP 和 WebSockets 都兼容的依赖项时,您可以定义一个参数来获取 HTTPConnection
而不是 Request
或 WebSocket
。
fastapi.Request
Request(scope, receive=empty_receive, send=empty_send)
基类:HTTPConnection
参数 |
描述 |
scope
|
类型: Scope
|
receive
|
类型: Receive 默认值: empty_receive
|
send
|
类型: Send 默认值: empty_send
|
源代码位于 starlette/requests.py
中
194
195
196
197
198
199
200
201 | def __init__(self, scope: Scope, receive: Receive = empty_receive, send: Send = empty_send):
super().__init__(scope)
assert scope["type"] == "http"
self._receive = receive
self._send = send
self._stream_consumed = False
self._is_disconnected = False
self._form = None
|
url_for
url_for(name, /, **path_params)
参数 |
描述 |
名称
|
类型: str
|
**path_params
|
类型: 任意 默认值: {}
|
源代码位于 starlette/requests.py
中
| def url_for(self, name: str, /, **path_params: typing.Any) -> URL:
router: Router = self.scope["router"]
url_path = router.url_path_for(name, **path_params)
return url_path.make_absolute_url(base_url=self.base_url)
|
stream 异步
源代码位于 starlette/requests.py
中
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229 | async def stream(self) -> typing.AsyncGenerator[bytes, None]:
if hasattr(self, "_body"):
yield self._body
yield b""
return
if self._stream_consumed:
raise RuntimeError("Stream consumed")
while not self._stream_consumed:
message = await self._receive()
if message["type"] == "http.request":
body = message.get("body", b"")
if not message.get("more_body", False):
self._stream_consumed = True
if body:
yield body
elif message["type"] == "http.disconnect":
self._is_disconnected = True
raise ClientDisconnect()
yield b""
|
body 异步
源代码位于 starlette/requests.py
中
231
232
233
234
235
236
237 | async def body(self) -> bytes:
if not hasattr(self, "_body"):
chunks: list[bytes] = []
async for chunk in self.stream():
chunks.append(chunk)
self._body = b"".join(chunks)
return self._body
|
json 异步
源代码位于 starlette/requests.py
中
| async def json(self) -> typing.Any:
if not hasattr(self, "_json"):
body = await self.body()
self._json = json.loads(body)
return self._json
|
form(*, max_files=1000, max_fields=1000)
参数 |
描述 |
最大文件数
|
类型: int | float 默认值: 1000
|
最大字段数
|
类型: int | float 默认值: 1000
|
源代码位于 starlette/requests.py
中
| def form(
self, *, max_files: int | float = 1000, max_fields: int | float = 1000
) -> AwaitableOrContextManager[FormData]:
return AwaitableOrContextManagerWrapper(self._get_form(max_files=max_files, max_fields=max_fields))
|
close 异步
源代码位于 starlette/requests.py
中
| async def close(self) -> None:
if self._form is not None:
await self._form.close()
|
is_disconnected 异步
源代码位于 starlette/requests.py
中
282
283
284
285
286
287
288
289
290
291
292
293
294 | async def is_disconnected(self) -> bool:
if not self._is_disconnected:
message: Message = {}
# If message isn't immediately available, move on
with anyio.CancelScope() as cs:
cs.cancel()
message = await self._receive()
if message.get("type") == "http.disconnect":
self._is_disconnected = True
return self._is_disconnected
|
send_push_promise 异步
源代码位于 starlette/requests.py
中
296
297
298
299
300
301
302 | async def send_push_promise(self, path: str) -> None:
if "http.response.push" in self.scope.get("extensions", {}):
raw_headers: list[tuple[bytes, bytes]] = []
for name in SERVER_PUSH_HEADERS_TO_COPY:
for value in self.headers.getlist(name):
raw_headers.append((name.encode("latin-1"), value.encode("latin-1")))
await self._send({"type": "http.response.push", "path": path, "headers": raw_headers})
|