Skip to content

๐Ÿ“จ ๐ŸŽš

โš™๏ธ Response ๐Ÿ”ข

๐Ÿ‘† ๐Ÿ’ช ๐Ÿ“ฃ ๐Ÿ”ข ๐Ÿ†Ž Response ๐Ÿ‘† โžก ๐Ÿ› ๏ธ ๐Ÿ”ข (๐Ÿ‘† ๐Ÿ’ช ๐Ÿช).

& โคด๏ธ ๐Ÿ‘† ๐Ÿ’ช โš’ ๐ŸŽš ๐Ÿ‘ˆ ๐Ÿ”€ ๐Ÿ“จ ๐ŸŽš.

from fastapi import FastAPI, Response

app = FastAPI()


@app.get("/headers-and-object/")
def get_headers(response: Response):
    response.headers["X-Cat-Dog"] = "alone in the world"
    return {"message": "Hello World"}

& โคด๏ธ ๐Ÿ‘† ๐Ÿ’ช ๐Ÿ“จ ๐Ÿ™† ๐ŸŽš ๐Ÿ‘† ๐Ÿ’ช, ๐Ÿ‘† ๐Ÿ›Ž ๐Ÿ”œ ( dict, ๐Ÿ’ฝ ๐Ÿท, โ™’๏ธ).

& ๐Ÿšฅ ๐Ÿ‘† ๐Ÿ“ฃ response_model, โšซ๏ธ ๐Ÿ”œ โš™๏ธ โ›ฝ & ๐Ÿ—œ ๐ŸŽš ๐Ÿ‘† ๐Ÿ“จ.

FastAPI ๐Ÿ”œ โš™๏ธ ๐Ÿ‘ˆ ๐Ÿ”€ ๐Ÿ“จ โš— ๐ŸŽš (๐Ÿช & ๐Ÿ‘” ๐Ÿ“Ÿ), & ๐Ÿ”œ ๐Ÿšฎ ๐Ÿ‘ซ ๐Ÿ ๐Ÿ“จ ๐Ÿ‘ˆ ๐Ÿ”Œ ๐Ÿ’ฒ ๐Ÿ‘† ๐Ÿ“จ, โ›ฝ ๐Ÿ™† response_model.

๐Ÿ‘† ๐Ÿ’ช ๐Ÿ“ฃ Response ๐Ÿ”ข ๐Ÿ”—, & โš’ ๐ŸŽš (& ๐Ÿช) ๐Ÿ‘ซ.

๐Ÿ“จ Response ๐Ÿ”—

๐Ÿ‘† ๐Ÿ’ช ๐Ÿšฎ ๐ŸŽš ๐Ÿ•โ” ๐Ÿ‘† ๐Ÿ“จ Response ๐Ÿ”—.

โœ ๐Ÿ“จ ๐Ÿ”ฌ ๐Ÿ“จ ๐Ÿ“จ ๐Ÿ”— & ๐Ÿšถโ€โ™€๏ธ ๐ŸŽš ๐ŸŒ– ๐Ÿ”ข:

from fastapi import FastAPI
from fastapi.responses import JSONResponse

app = FastAPI()


@app.get("/headers/")
def get_headers():
    content = {"message": "Hello World"}
    headers = {"X-Cat-Dog": "alone in the world", "Content-Language": "en-US"}
    return JSONResponse(content=content, headers=headers)

๐Ÿ“ก โ„น

๐Ÿ‘† ๐Ÿ’ช โš™๏ธ from starlette.responses import Response โš–๏ธ from starlette.responses import JSONResponse.

FastAPI ๐Ÿšš ๐ŸŽ starlette.responses fastapi.responses ๐Ÿช ๐Ÿ‘†, ๐Ÿ‘ฉโ€๐Ÿ’ป. โœ‹๏ธ ๐ŸŒ… ๐Ÿ’ช ๐Ÿ“จ ๐Ÿ‘Ÿ ๐Ÿ”— โšช๏ธโžก๏ธ ๐Ÿ’ƒ.

& Response ๐Ÿ’ช โš™๏ธ ๐Ÿ›Ž โš’ ๐ŸŽš & ๐Ÿช, FastAPI ๐Ÿšš โšซ๏ธ fastapi.Response.

๐Ÿ›ƒ ๐ŸŽš

โœ”๏ธ ๐Ÿคฏ ๐Ÿ‘ˆ ๐Ÿ›ƒ ยฉ ๐ŸŽš ๐Ÿ’ช ๐Ÿšฎ โš™๏ธ 'โœ–-' ๐Ÿ”ก.

โœ‹๏ธ ๐Ÿšฅ ๐Ÿ‘† โœ”๏ธ ๐Ÿ›ƒ ๐ŸŽš ๐Ÿ‘ˆ ๐Ÿ‘† ๐Ÿ’š ๐Ÿ‘ฉโ€๐Ÿ’ป ๐Ÿ–ฅ ๐Ÿ’ช ๐Ÿ‘€, ๐Ÿ‘† ๐Ÿ’ช ๐Ÿšฎ ๐Ÿ‘ซ ๐Ÿ‘† โšœ ๐Ÿ“ณ (โœ ๐ŸŒ… โšœ (โœ–๏ธ-๐Ÿ‡จ๐Ÿ‡ณ โ„น ๐Ÿค)), โš™๏ธ ๐Ÿ”ข expose_headers ๐Ÿ“„ ๐Ÿ’ƒ โšœ ๐Ÿฉบ.