Skip to content

๐Ÿ“จ ๐Ÿช

โš™๏ธ Response ๐Ÿ”ข

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

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

from fastapi import FastAPI, Response

app = FastAPI()


@app.post("/cookie-and-object/")
def create_cookie(response: Response):
    response.set_cookie(key="fakesession", value="fake-cookie-session-value")
    return {"message": "Come to the dark side, we have cookies"}

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

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

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

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

๐Ÿ“จ Response ๐Ÿ”—

๐Ÿ‘† ๐Ÿ’ช โœ ๐Ÿช ๐Ÿ•โ” ๐Ÿ›ฌ Response ๐Ÿ”— ๐Ÿ‘† ๐Ÿ“Ÿ.

๐Ÿ‘ˆ, ๐Ÿ‘† ๐Ÿ’ช โœ ๐Ÿ“จ ๐Ÿ”ฌ ๐Ÿ“จ ๐Ÿ“จ ๐Ÿ”—.

โคด๏ธ โš’ ๐Ÿช โšซ๏ธ, & โคด๏ธ ๐Ÿ“จ โšซ๏ธ:

from fastapi import FastAPI
from fastapi.responses import JSONResponse

app = FastAPI()


@app.post("/cookie/")
def create_cookie():
    content = {"message": "Come to the dark side, we have cookies"}
    response = JSONResponse(content=content)
    response.set_cookie(key="fakesession", value="fake-cookie-session-value")
    return response

Tip

โœ”๏ธ ๐Ÿคฏ ๐Ÿ‘ˆ ๐Ÿšฅ ๐Ÿ‘† ๐Ÿ“จ ๐Ÿ“จ ๐Ÿ”— โ†ฉ๏ธ โš™๏ธ Response ๐Ÿ”ข, FastAPI ๐Ÿ”œ ๐Ÿ“จ โšซ๏ธ ๐Ÿ”—.

, ๐Ÿ‘† ๐Ÿ”œ โœ”๏ธ โš’ ๐Ÿ’ญ ๐Ÿ‘† ๐Ÿ’ฝ โ˜‘ ๐Ÿ†Ž. ๐Ÿคถ โ“‚. โšซ๏ธ ๐Ÿ”— โฎ๏ธ ๐ŸŽป, ๐Ÿšฅ ๐Ÿ‘† ๐Ÿ›ฌ JSONResponse.

& ๐Ÿ‘ˆ ๐Ÿ‘† ๐Ÿšซ ๐Ÿ“จ ๐Ÿ™† ๐Ÿ“Š ๐Ÿ‘ˆ ๐Ÿ”œ โœ”๏ธ โ›ฝ response_model.

๐ŸŒ… โ„น

๐Ÿ“ก โ„น

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

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

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

๐Ÿ‘€ ๐ŸŒ ๐Ÿ’ช ๐Ÿ”ข & ๐ŸŽ›, โœ… ๐Ÿงพ ๐Ÿ’ƒ.