{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# {class}`~starlette.requests.Request`\n", "\n", "参考:[Request](https://fastapi.tiangolo.com/zh/advanced/using-request-directly/)\n", "\n", "假设你想在你的路径操作函数中获取客户端的 IP 地址/主机。\n", "\n", "为此,你需要直接访问请求对象。" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "from fastapi import FastAPI\n", "from starlette.requests import Request\n", "\n", "app = FastAPI()\n", "\n", "\n", "@app.get(\"/items/{item_id}\")\n", "def read_root(item_id: str, request: Request):\n", " client_host = request.client.host\n", " return {\"client_host\": client_host, \"item_id\": item_id}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "通过声明路径操作函数参数,并将其类型设置为 {class}`~starlette.requests.Request`,FastAPI 就会知道将 {class}`~starlette.requests.Request` 传递给那个参数。" ] } ], "metadata": { "kernelspec": { "display_name": "py311", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.7" } }, "nbformat": 4, "nbformat_minor": 2 }