跳至內容

Custom Response Classes - File, HTML, Redirect, Streaming, etc.(自訂回應類別 - 檔案、HTML、重定向、串流等)

您可以使用多個自訂回應類別來建立實例,並直接從您的*路徑操作*傳回它們。

FastAPI 自訂回應文件 - HTML、串流、檔案等中了解更多相關資訊。

您可以直接從 fastapi.responses 導入它們。

from fastapi.responses import (
    FileResponse,
    HTMLResponse,
    JSONResponse,
    ORJSONResponse,
    PlainTextResponse,
    RedirectResponse,
    Response,
    StreamingResponse,
    UJSONResponse,
)

FastAPI 回應

有一些自訂的 FastAPI 回應類別,您可以使用它們來最佳化 JSON 效能。

fastapi.responses.UJSONResponse

UJSONResponse(
    content,
    status_code=200,
    headers=None,
    media_type=None,
    background=None,
)

基底:JSONResponse

使用高效能 ujson 函式庫將資料序列化為 JSON 的 JSON 回應。

FastAPI 自訂回應文件 - HTML、串流、檔案等中了解更多相關資訊。

參數 說明
content(內容)

類型: Any(任何)

status_code(狀態碼)

類型: int(整數) 預設值: 200

headers(標頭)

類型: Mapping[str, str] | None(字串對應或無) 預設值: None(無)

media_type(媒體類型)

類型: str | None(字串或無) 預設值: None(無)

background(背景)

類型: BackgroundTask | None(背景任務或無) 預設值: None(無)

原始程式碼位於 starlette/responses.py
170
171
172
173
174
175
176
177
178
def __init__(
    self,
    content: typing.Any,
    status_code: int = 200,
    headers: typing.Mapping[str, str] | None = None,
    media_type: str | None = None,
    background: BackgroundTask | None = None,
) -> None:
    super().__init__(content, status_code, headers, media_type, background)

charset(字元集) 類別屬性 實例屬性

charset = 'utf-8'

status_code(狀態碼) 實例屬性

status_code = status_code

media_type 類別屬性 實例屬性

media_type = 'application/json'

body 實例屬性

body = render(content)

background 實例屬性

background = background

headers 屬性

headers

render

render(content)
參數 說明
content(內容)

類型: Any(任何)

原始碼位於 fastapi/responses.py
31
32
33
def render(self, content: Any) -> bytes:
    assert ujson is not None, "ujson must be installed to use UJSONResponse"
    return ujson.dumps(content, ensure_ascii=False).encode("utf-8")

init_headers

init_headers(headers=None)
參數 說明
headers(標頭)

類型: Mapping[str, str] | None(字串對應或無) 預設值: None(無)

原始程式碼位於 starlette/responses.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def init_headers(self, headers: typing.Mapping[str, str] | None = None) -> None:
    if headers is None:
        raw_headers: list[tuple[bytes, bytes]] = []
        populate_content_length = True
        populate_content_type = True
    else:
        raw_headers = [(k.lower().encode("latin-1"), v.encode("latin-1")) for k, v in headers.items()]
        keys = [h[0] for h in raw_headers]
        populate_content_length = b"content-length" not in keys
        populate_content_type = b"content-type" not in keys

    body = getattr(self, "body", None)
    if (
        body is not None
        and populate_content_length
        and not (self.status_code < 200 or self.status_code in (204, 304))
    ):
        content_length = str(len(body))
        raw_headers.append((b"content-length", content_length.encode("latin-1")))

    content_type = self.media_type
    if content_type is not None and populate_content_type:
        if content_type.startswith("text/") and "charset=" not in content_type.lower():
            content_type += "; charset=" + self.charset
        raw_headers.append((b"content-type", content_type.encode("latin-1")))

    self.raw_headers = raw_headers
set_cookie(
    key,
    value="",
    max_age=None,
    expires=None,
    path="/",
    domain=None,
    secure=False,
    httponly=False,
    samesite="lax",
)
參數 說明
鍵值 (key)

類型: str

數值 (value)

類型: str 預設值: ''

最大存活時間 (max_age)

類型: int | None 預設值: None

到期時間 (expires)

類型: datetime | str | int | None 預設值: None

路徑 (path)

類型: str | None 預設值: '/'

網域 (domain)

類型: str | None(字串或無) 預設值: None(無)

安全連線 (secure)

類型: bool 預設值: False

僅限 HTTP (httponly)

類型: bool 預設值: False

SameSite 屬性 (samesite)

類型: Literal['lax', 'strict', 'none'] | None 預設值: 'lax'

原始程式碼位於 starlette/responses.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def set_cookie(
    self,
    key: str,
    value: str = "",
    max_age: int | None = None,
    expires: datetime | str | int | None = None,
    path: str | None = "/",
    domain: str | None = None,
    secure: bool = False,
    httponly: bool = False,
    samesite: typing.Literal["lax", "strict", "none"] | None = "lax",
) -> None:
    cookie: http.cookies.BaseCookie[str] = http.cookies.SimpleCookie()
    cookie[key] = value
    if max_age is not None:
        cookie[key]["max-age"] = max_age
    if expires is not None:
        if isinstance(expires, datetime):
            cookie[key]["expires"] = format_datetime(expires, usegmt=True)
        else:
            cookie[key]["expires"] = expires
    if path is not None:
        cookie[key]["path"] = path
    if domain is not None:
        cookie[key]["domain"] = domain
    if secure:
        cookie[key]["secure"] = True
    if httponly:
        cookie[key]["httponly"] = True
    if samesite is not None:
        assert samesite.lower() in [
            "strict",
            "lax",
            "none",
        ], "samesite must be either 'strict', 'lax' or 'none'"
        cookie[key]["samesite"] = samesite
    cookie_val = cookie.output(header="").strip()
    self.raw_headers.append((b"set-cookie", cookie_val.encode("latin-1")))
delete_cookie(
    key,
    path="/",
    domain=None,
    secure=False,
    httponly=False,
    samesite="lax",
)
參數 說明
鍵值 (key)

類型: str

路徑 (path)

類型: str 預設值: '/'

網域 (domain)

類型: str | None(字串或無) 預設值: None(無)

安全連線 (secure)

類型: bool 預設值: False

僅限 HTTP (httponly)

類型: bool 預設值: False

SameSite 屬性 (samesite)

類型: Literal['lax', 'strict', 'none'] | None 預設值: 'lax'

原始程式碼位於 starlette/responses.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def delete_cookie(
    self,
    key: str,
    path: str = "/",
    domain: str | None = None,
    secure: bool = False,
    httponly: bool = False,
    samesite: typing.Literal["lax", "strict", "none"] | None = "lax",
) -> None:
    self.set_cookie(
        key,
        max_age=0,
        expires=0,
        path=path,
        domain=domain,
        secure=secure,
        httponly=httponly,
        samesite=samesite,
    )

fastapi.responses.ORJSONResponse

ORJSONResponse(
    content,
    status_code=200,
    headers=None,
    media_type=None,
    background=None,
)

基底:JSONResponse

使用高效能 orjson 函式庫將資料序列化為 JSON 的 JSON 回應。

FastAPI 自訂回應文件 - HTML、串流、檔案等中了解更多相關資訊。

參數 說明
content(內容)

類型: Any(任何)

status_code(狀態碼)

類型: int(整數) 預設值: 200

headers(標頭)

類型: Mapping[str, str] | None(字串對應或無) 預設值: None(無)

media_type(媒體類型)

類型: str | None(字串或無) 預設值: None(無)

background(背景)

類型: BackgroundTask | None(背景任務或無) 預設值: None(無)

原始程式碼位於 starlette/responses.py
170
171
172
173
174
175
176
177
178
def __init__(
    self,
    content: typing.Any,
    status_code: int = 200,
    headers: typing.Mapping[str, str] | None = None,
    media_type: str | None = None,
    background: BackgroundTask | None = None,
) -> None:
    super().__init__(content, status_code, headers, media_type, background)

charset 類別屬性 實例屬性

charset = 'utf-8'

status_code 實例屬性

status_code = status_code

media_type 類別屬性 實例屬性

media_type = 'application/json'

body 實例屬性

body = render(content)

background 實例屬性

background = background

headers 屬性

headers

render

render(content)
參數 說明
content(內容)

類型: Any(任何)

原始碼位於 fastapi/responses.py
44
45
46
47
48
def render(self, content: Any) -> bytes:
    assert orjson is not None, "orjson must be installed to use ORJSONResponse"
    return orjson.dumps(
        content, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SERIALIZE_NUMPY
    )

init_headers

init_headers(headers=None)
參數 說明
headers(標頭)

類型: Mapping[str, str] | None(字串對應或無) 預設值: None(無)

原始程式碼位於 starlette/responses.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def init_headers(self, headers: typing.Mapping[str, str] | None = None) -> None:
    if headers is None:
        raw_headers: list[tuple[bytes, bytes]] = []
        populate_content_length = True
        populate_content_type = True
    else:
        raw_headers = [(k.lower().encode("latin-1"), v.encode("latin-1")) for k, v in headers.items()]
        keys = [h[0] for h in raw_headers]
        populate_content_length = b"content-length" not in keys
        populate_content_type = b"content-type" not in keys

    body = getattr(self, "body", None)
    if (
        body is not None
        and populate_content_length
        and not (self.status_code < 200 or self.status_code in (204, 304))
    ):
        content_length = str(len(body))
        raw_headers.append((b"content-length", content_length.encode("latin-1")))

    content_type = self.media_type
    if content_type is not None and populate_content_type:
        if content_type.startswith("text/") and "charset=" not in content_type.lower():
            content_type += "; charset=" + self.charset
        raw_headers.append((b"content-type", content_type.encode("latin-1")))

    self.raw_headers = raw_headers
set_cookie(
    key,
    value="",
    max_age=None,
    expires=None,
    path="/",
    domain=None,
    secure=False,
    httponly=False,
    samesite="lax",
)
參數 說明
鍵值 (key)

類型: str

數值 (value)

類型: str 預設值: ''

最大存活時間 (max_age)

類型: int | None 預設值: None

到期時間 (expires)

類型: datetime | str | int | None 預設值: None

路徑 (path)

類型: str | None 預設值: '/'

網域 (domain)

類型: str | None(字串或無) 預設值: None(無)

安全連線 (secure)

類型: bool 預設值: False

僅限 HTTP (httponly)

類型: bool 預設值: False

SameSite 屬性 (samesite)

類型: Literal['lax', 'strict', 'none'] | None 預設值: 'lax'

原始程式碼位於 starlette/responses.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def set_cookie(
    self,
    key: str,
    value: str = "",
    max_age: int | None = None,
    expires: datetime | str | int | None = None,
    path: str | None = "/",
    domain: str | None = None,
    secure: bool = False,
    httponly: bool = False,
    samesite: typing.Literal["lax", "strict", "none"] | None = "lax",
) -> None:
    cookie: http.cookies.BaseCookie[str] = http.cookies.SimpleCookie()
    cookie[key] = value
    if max_age is not None:
        cookie[key]["max-age"] = max_age
    if expires is not None:
        if isinstance(expires, datetime):
            cookie[key]["expires"] = format_datetime(expires, usegmt=True)
        else:
            cookie[key]["expires"] = expires
    if path is not None:
        cookie[key]["path"] = path
    if domain is not None:
        cookie[key]["domain"] = domain
    if secure:
        cookie[key]["secure"] = True
    if httponly:
        cookie[key]["httponly"] = True
    if samesite is not None:
        assert samesite.lower() in [
            "strict",
            "lax",
            "none",
        ], "samesite must be either 'strict', 'lax' or 'none'"
        cookie[key]["samesite"] = samesite
    cookie_val = cookie.output(header="").strip()
    self.raw_headers.append((b"set-cookie", cookie_val.encode("latin-1")))
delete_cookie(
    key,
    path="/",
    domain=None,
    secure=False,
    httponly=False,
    samesite="lax",
)
參數 說明
鍵值 (key)

類型: str

路徑 (path)

類型: str 預設值: '/'

網域 (domain)

類型: str | None(字串或無) 預設值: None(無)

安全連線 (secure)

類型: bool 預設值: False

僅限 HTTP (httponly)

類型: bool 預設值: False

SameSite 屬性 (samesite)

類型: Literal['lax', 'strict', 'none'] | None 預設值: 'lax'

原始程式碼位於 starlette/responses.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def delete_cookie(
    self,
    key: str,
    path: str = "/",
    domain: str | None = None,
    secure: bool = False,
    httponly: bool = False,
    samesite: typing.Literal["lax", "strict", "none"] | None = "lax",
) -> None:
    self.set_cookie(
        key,
        max_age=0,
        expires=0,
        path=path,
        domain=domain,
        secure=secure,
        httponly=httponly,
        samesite=samesite,
    )

Starlette 回應

fastapi.responses.FileResponse

FileResponse(
    path,
    status_code=200,
    headers=None,
    media_type=None,
    background=None,
    filename=None,
    stat_result=None,
    method=None,
    content_disposition_type="attachment",
)

基底類別: Response

參數 說明
路徑 (path)

類型: str | PathLike[str]

status_code(狀態碼)

類型: int(整數) 預設值: 200

headers(標頭)

類型: Mapping[str, str] | None(字串對應或無) 預設值: None(無)

media_type(媒體類型)

類型: str | None(字串或無) 預設值: None(無)

background(背景)

類型: BackgroundTask | None(背景任務或無) 預設值: None(無)

filename(檔案名稱)

類型: str | None(字串或無) 預設值: None(無)

stat_result(檔案狀態結果)

類型: stat_result | None 預設值: None

method(方法)

類型: str | None(字串或無) 預設值: None(無)

content_disposition_type(內容配置類型)

類型: str 預設值: 'attachment'

原始程式碼位於 starlette/responses.py
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
def __init__(
    self,
    path: str | os.PathLike[str],
    status_code: int = 200,
    headers: typing.Mapping[str, str] | None = None,
    media_type: str | None = None,
    background: BackgroundTask | None = None,
    filename: str | None = None,
    stat_result: os.stat_result | None = None,
    method: str | None = None,
    content_disposition_type: str = "attachment",
) -> None:
    self.path = path
    self.status_code = status_code
    self.filename = filename
    if method is not None:
        warnings.warn(
            "The 'method' parameter is not used, and it will be removed.",
            DeprecationWarning,
        )
    if media_type is None:
        media_type = guess_type(filename or path)[0] or "text/plain"
    self.media_type = media_type
    self.background = background
    self.init_headers(headers)
    if self.filename is not None:
        content_disposition_filename = quote(self.filename)
        if content_disposition_filename != self.filename:
            content_disposition = f"{content_disposition_type}; filename*=utf-8''{content_disposition_filename}"
        else:
            content_disposition = f'{content_disposition_type}; filename="{self.filename}"'
        self.headers.setdefault("content-disposition", content_disposition)
    self.stat_result = stat_result
    if stat_result is not None:
        self.set_stat_headers(stat_result)

chunk_size 類別屬性 實例屬性

chunk_size = 64 * 1024

charset 類別屬性 實例屬性

charset = 'utf-8'

status_code 實例屬性

status_code = status_code

media_type 實例屬性

media_type = media_type

body 實例屬性

body = render(content)

background 實例屬性

background = background

headers 屬性

headers

render

render(content)
參數 說明
content(內容)

類型: Any(任何)

原始程式碼位於 starlette/responses.py
44
45
46
47
48
49
def render(self, content: typing.Any) -> bytes | memoryview:
    if content is None:
        return b""
    if isinstance(content, (bytes, memoryview)):
        return content
    return content.encode(self.charset)  # type: ignore

init_headers

init_headers(headers=None)
參數 說明
headers(標頭)

類型: Mapping[str, str] | None(字串對應或無) 預設值: None(無)

原始程式碼位於 starlette/responses.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def init_headers(self, headers: typing.Mapping[str, str] | None = None) -> None:
    if headers is None:
        raw_headers: list[tuple[bytes, bytes]] = []
        populate_content_length = True
        populate_content_type = True
    else:
        raw_headers = [(k.lower().encode("latin-1"), v.encode("latin-1")) for k, v in headers.items()]
        keys = [h[0] for h in raw_headers]
        populate_content_length = b"content-length" not in keys
        populate_content_type = b"content-type" not in keys

    body = getattr(self, "body", None)
    if (
        body is not None
        and populate_content_length
        and not (self.status_code < 200 or self.status_code in (204, 304))
    ):
        content_length = str(len(body))
        raw_headers.append((b"content-length", content_length.encode("latin-1")))

    content_type = self.media_type
    if content_type is not None and populate_content_type:
        if content_type.startswith("text/") and "charset=" not in content_type.lower():
            content_type += "; charset=" + self.charset
        raw_headers.append((b"content-type", content_type.encode("latin-1")))

    self.raw_headers = raw_headers
set_cookie(
    key,
    value="",
    max_age=None,
    expires=None,
    path="/",
    domain=None,
    secure=False,
    httponly=False,
    samesite="lax",
)
參數 說明
鍵值 (key)

類型: str

數值 (value)

類型: str 預設值: ''

最大存活時間 (max_age)

類型: int | None 預設值: None

到期時間 (expires)

類型: datetime | str | int | None 預設值: None

路徑 (path)

類型: str | None 預設值: '/'

網域 (domain)

類型: str | None(字串或無) 預設值: None(無)

安全連線 (secure)

類型: bool 預設值: False

僅限 HTTP (httponly)

類型: bool 預設值: False

SameSite 屬性 (samesite)

類型: Literal['lax', 'strict', 'none'] | None 預設值: 'lax'

原始程式碼位於 starlette/responses.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def set_cookie(
    self,
    key: str,
    value: str = "",
    max_age: int | None = None,
    expires: datetime | str | int | None = None,
    path: str | None = "/",
    domain: str | None = None,
    secure: bool = False,
    httponly: bool = False,
    samesite: typing.Literal["lax", "strict", "none"] | None = "lax",
) -> None:
    cookie: http.cookies.BaseCookie[str] = http.cookies.SimpleCookie()
    cookie[key] = value
    if max_age is not None:
        cookie[key]["max-age"] = max_age
    if expires is not None:
        if isinstance(expires, datetime):
            cookie[key]["expires"] = format_datetime(expires, usegmt=True)
        else:
            cookie[key]["expires"] = expires
    if path is not None:
        cookie[key]["path"] = path
    if domain is not None:
        cookie[key]["domain"] = domain
    if secure:
        cookie[key]["secure"] = True
    if httponly:
        cookie[key]["httponly"] = True
    if samesite is not None:
        assert samesite.lower() in [
            "strict",
            "lax",
            "none",
        ], "samesite must be either 'strict', 'lax' or 'none'"
        cookie[key]["samesite"] = samesite
    cookie_val = cookie.output(header="").strip()
    self.raw_headers.append((b"set-cookie", cookie_val.encode("latin-1")))
delete_cookie(
    key,
    path="/",
    domain=None,
    secure=False,
    httponly=False,
    samesite="lax",
)
參數 說明
鍵值 (key)

類型: str

路徑 (path)

類型: str 預設值: '/'

網域 (domain)

類型: str | None(字串或無) 預設值: None(無)

安全連線 (secure)

類型: bool 預設值: False

僅限 HTTP (httponly)

類型: bool 預設值: False

SameSite 屬性 (samesite)

類型: Literal['lax', 'strict', 'none'] | None 預設值: 'lax'

原始程式碼位於 starlette/responses.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def delete_cookie(
    self,
    key: str,
    path: str = "/",
    domain: str | None = None,
    secure: bool = False,
    httponly: bool = False,
    samesite: typing.Literal["lax", "strict", "none"] | None = "lax",
) -> None:
    self.set_cookie(
        key,
        max_age=0,
        expires=0,
        path=path,
        domain=domain,
        secure=secure,
        httponly=httponly,
        samesite=samesite,
    )

fastapi.responses.HTMLResponse

HTMLResponse(
    content=None,
    status_code=200,
    headers=None,
    media_type=None,
    background=None,
)

基底類別: Response

參數 說明
content(內容)

類型: 任何 預設值:

status_code(狀態碼)

類型: int(整數) 預設值: 200

headers(標頭)

類型: Mapping[str, str] | None(字串對應或無) 預設值: None(無)

media_type(媒體類型)

類型: str | None(字串或無) 預設值: None(無)

background(背景)

類型: BackgroundTask | None(背景任務或無) 預設值: None(無)

原始程式碼位於 starlette/responses.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
def __init__(
    self,
    content: typing.Any = None,
    status_code: int = 200,
    headers: typing.Mapping[str, str] | None = None,
    media_type: str | None = None,
    background: BackgroundTask | None = None,
) -> None:
    self.status_code = status_code
    if media_type is not None:
        self.media_type = media_type
    self.background = background
    self.body = self.render(content)
    self.init_headers(headers)

charset 類別屬性 實例屬性

charset = 'utf-8'

status_code 實例屬性

status_code = status_code

media_type 類別屬性 實例屬性

media_type = 'text/html'

body 實例屬性

body = render(content)

background 實例屬性

background = background

headers 屬性

headers

render

render(content)
參數 說明
content(內容)

類型: Any(任何)

原始程式碼位於 starlette/responses.py
44
45
46
47
48
49
def render(self, content: typing.Any) -> bytes | memoryview:
    if content is None:
        return b""
    if isinstance(content, (bytes, memoryview)):
        return content
    return content.encode(self.charset)  # type: ignore

init_headers

init_headers(headers=None)
參數 說明
headers(標頭)

類型: Mapping[str, str] | None(字串對應或無) 預設值: None(無)

原始程式碼位於 starlette/responses.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def init_headers(self, headers: typing.Mapping[str, str] | None = None) -> None:
    if headers is None:
        raw_headers: list[tuple[bytes, bytes]] = []
        populate_content_length = True
        populate_content_type = True
    else:
        raw_headers = [(k.lower().encode("latin-1"), v.encode("latin-1")) for k, v in headers.items()]
        keys = [h[0] for h in raw_headers]
        populate_content_length = b"content-length" not in keys
        populate_content_type = b"content-type" not in keys

    body = getattr(self, "body", None)
    if (
        body is not None
        and populate_content_length
        and not (self.status_code < 200 or self.status_code in (204, 304))
    ):
        content_length = str(len(body))
        raw_headers.append((b"content-length", content_length.encode("latin-1")))

    content_type = self.media_type
    if content_type is not None and populate_content_type:
        if content_type.startswith("text/") and "charset=" not in content_type.lower():
            content_type += "; charset=" + self.charset
        raw_headers.append((b"content-type", content_type.encode("latin-1")))

    self.raw_headers = raw_headers
set_cookie(
    key,
    value="",
    max_age=None,
    expires=None,
    path="/",
    domain=None,
    secure=False,
    httponly=False,
    samesite="lax",
)
參數 說明
鍵值 (key)

類型: str

數值 (value)

類型: str 預設值: ''

最大存活時間 (max_age)

類型: int | None 預設值: None

到期時間 (expires)

類型: datetime | str | int | None 預設值: None

路徑 (path)

類型: str | None 預設值: '/'

網域 (domain)

類型: str | None(字串或無) 預設值: None(無)

安全連線 (secure)

類型: bool 預設值: False

僅限 HTTP (httponly)

類型: bool 預設值: False

SameSite 屬性 (samesite)

類型: Literal['lax', 'strict', 'none'] | None 預設值: 'lax'

原始程式碼位於 starlette/responses.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def set_cookie(
    self,
    key: str,
    value: str = "",
    max_age: int | None = None,
    expires: datetime | str | int | None = None,
    path: str | None = "/",
    domain: str | None = None,
    secure: bool = False,
    httponly: bool = False,
    samesite: typing.Literal["lax", "strict", "none"] | None = "lax",
) -> None:
    cookie: http.cookies.BaseCookie[str] = http.cookies.SimpleCookie()
    cookie[key] = value
    if max_age is not None:
        cookie[key]["max-age"] = max_age
    if expires is not None:
        if isinstance(expires, datetime):
            cookie[key]["expires"] = format_datetime(expires, usegmt=True)
        else:
            cookie[key]["expires"] = expires
    if path is not None:
        cookie[key]["path"] = path
    if domain is not None:
        cookie[key]["domain"] = domain
    if secure:
        cookie[key]["secure"] = True
    if httponly:
        cookie[key]["httponly"] = True
    if samesite is not None:
        assert samesite.lower() in [
            "strict",
            "lax",
            "none",
        ], "samesite must be either 'strict', 'lax' or 'none'"
        cookie[key]["samesite"] = samesite
    cookie_val = cookie.output(header="").strip()
    self.raw_headers.append((b"set-cookie", cookie_val.encode("latin-1")))
delete_cookie(
    key,
    path="/",
    domain=None,
    secure=False,
    httponly=False,
    samesite="lax",
)
參數 說明
鍵值 (key)

類型: str

路徑 (path)

類型: str 預設值: '/'

網域 (domain)

類型: str | None(字串或無) 預設值: None(無)

安全連線 (secure)

類型: bool 預設值: False

僅限 HTTP (httponly)

類型: bool 預設值: False

SameSite 屬性 (samesite)

類型: Literal['lax', 'strict', 'none'] | None 預設值: 'lax'

原始程式碼位於 starlette/responses.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def delete_cookie(
    self,
    key: str,
    path: str = "/",
    domain: str | None = None,
    secure: bool = False,
    httponly: bool = False,
    samesite: typing.Literal["lax", "strict", "none"] | None = "lax",
) -> None:
    self.set_cookie(
        key,
        max_age=0,
        expires=0,
        path=path,
        domain=domain,
        secure=secure,
        httponly=httponly,
        samesite=samesite,
    )

fastapi.responses.JSONResponse

JSONResponse(
    content,
    status_code=200,
    headers=None,
    media_type=None,
    background=None,
)

基底類別: Response

參數 說明
content(內容)

類型: Any(任何)

status_code(狀態碼)

類型: int(整數) 預設值: 200

headers(標頭)

類型: Mapping[str, str] | None(字串對應或無) 預設值: None(無)

media_type(媒體類型)

類型: str | None(字串或無) 預設值: None(無)

background(背景)

類型: BackgroundTask | None(背景任務或無) 預設值: None(無)

原始程式碼位於 starlette/responses.py
170
171
172
173
174
175
176
177
178
def __init__(
    self,
    content: typing.Any,
    status_code: int = 200,
    headers: typing.Mapping[str, str] | None = None,
    media_type: str | None = None,
    background: BackgroundTask | None = None,
) -> None:
    super().__init__(content, status_code, headers, media_type, background)

charset 類別屬性 實例屬性

charset = 'utf-8'

status_code 實例屬性

status_code = status_code

media_type 類別屬性 實例屬性

media_type = 'application/json'

body 實例屬性

body = render(content)

background 實例屬性

background = background

headers 屬性

headers

render

render(content)
參數 說明
content(內容)

類型: Any(任何)

原始程式碼位於 starlette/responses.py
180
181
182
183
184
185
186
187
def render(self, content: typing.Any) -> bytes:
    return json.dumps(
        content,
        ensure_ascii=False,
        allow_nan=False,
        indent=None,
        separators=(",", ":"),
    ).encode("utf-8")

init_headers

init_headers(headers=None)
參數 說明
headers(標頭)

類型: Mapping[str, str] | None(字串對應或無) 預設值: None(無)

原始程式碼位於 starlette/responses.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def init_headers(self, headers: typing.Mapping[str, str] | None = None) -> None:
    if headers is None:
        raw_headers: list[tuple[bytes, bytes]] = []
        populate_content_length = True
        populate_content_type = True
    else:
        raw_headers = [(k.lower().encode("latin-1"), v.encode("latin-1")) for k, v in headers.items()]
        keys = [h[0] for h in raw_headers]
        populate_content_length = b"content-length" not in keys
        populate_content_type = b"content-type" not in keys

    body = getattr(self, "body", None)
    if (
        body is not None
        and populate_content_length
        and not (self.status_code < 200 or self.status_code in (204, 304))
    ):
        content_length = str(len(body))
        raw_headers.append((b"content-length", content_length.encode("latin-1")))

    content_type = self.media_type
    if content_type is not None and populate_content_type:
        if content_type.startswith("text/") and "charset=" not in content_type.lower():
            content_type += "; charset=" + self.charset
        raw_headers.append((b"content-type", content_type.encode("latin-1")))

    self.raw_headers = raw_headers
set_cookie(
    key,
    value="",
    max_age=None,
    expires=None,
    path="/",
    domain=None,
    secure=False,
    httponly=False,
    samesite="lax",
)
參數 說明
鍵值 (key)

類型: str

數值 (value)

類型: str 預設值: ''

最大存活時間 (max_age)

類型: int | None 預設值: None

到期時間 (expires)

類型: datetime | str | int | None 預設值: None

路徑 (path)

類型: str | None 預設值: '/'

網域 (domain)

類型: str | None(字串或無) 預設值: None(無)

安全連線 (secure)

類型: bool 預設值: False

僅限 HTTP (httponly)

類型: bool 預設值: False

SameSite 屬性 (samesite)

類型: Literal['lax', 'strict', 'none'] | None 預設值: 'lax'

原始程式碼位於 starlette/responses.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def set_cookie(
    self,
    key: str,
    value: str = "",
    max_age: int | None = None,
    expires: datetime | str | int | None = None,
    path: str | None = "/",
    domain: str | None = None,
    secure: bool = False,
    httponly: bool = False,
    samesite: typing.Literal["lax", "strict", "none"] | None = "lax",
) -> None:
    cookie: http.cookies.BaseCookie[str] = http.cookies.SimpleCookie()
    cookie[key] = value
    if max_age is not None:
        cookie[key]["max-age"] = max_age
    if expires is not None:
        if isinstance(expires, datetime):
            cookie[key]["expires"] = format_datetime(expires, usegmt=True)
        else:
            cookie[key]["expires"] = expires
    if path is not None:
        cookie[key]["path"] = path
    if domain is not None:
        cookie[key]["domain"] = domain
    if secure:
        cookie[key]["secure"] = True
    if httponly:
        cookie[key]["httponly"] = True
    if samesite is not None:
        assert samesite.lower() in [
            "strict",
            "lax",
            "none",
        ], "samesite must be either 'strict', 'lax' or 'none'"
        cookie[key]["samesite"] = samesite
    cookie_val = cookie.output(header="").strip()
    self.raw_headers.append((b"set-cookie", cookie_val.encode("latin-1")))
delete_cookie(
    key,
    path="/",
    domain=None,
    secure=False,
    httponly=False,
    samesite="lax",
)
參數 說明
鍵值 (key)

類型: str

路徑 (path)

類型: str 預設值: '/'

網域 (domain)

類型: str | None(字串或無) 預設值: None(無)

安全連線 (secure)

類型: bool 預設值: False

僅限 HTTP (httponly)

類型: bool 預設值: False

SameSite 屬性 (samesite)

類型: Literal['lax', 'strict', 'none'] | None 預設值: 'lax'

原始程式碼位於 starlette/responses.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def delete_cookie(
    self,
    key: str,
    path: str = "/",
    domain: str | None = None,
    secure: bool = False,
    httponly: bool = False,
    samesite: typing.Literal["lax", "strict", "none"] | None = "lax",
) -> None:
    self.set_cookie(
        key,
        max_age=0,
        expires=0,
        path=path,
        domain=domain,
        secure=secure,
        httponly=httponly,
        samesite=samesite,
    )

fastapi.responses.PlainTextResponse

PlainTextResponse(
    content=None,
    status_code=200,
    headers=None,
    media_type=None,
    background=None,
)

基底類別: Response

參數 說明
content(內容)

類型: 任何 預設值:

status_code(狀態碼)

類型: int(整數) 預設值: 200

headers(標頭)

類型: Mapping[str, str] | None(字串對應或無) 預設值: None(無)

media_type(媒體類型)

類型: str | None(字串或無) 預設值: None(無)

background(背景)

類型: BackgroundTask | None(背景任務或無) 預設值: None(無)

原始程式碼位於 starlette/responses.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
def __init__(
    self,
    content: typing.Any = None,
    status_code: int = 200,
    headers: typing.Mapping[str, str] | None = None,
    media_type: str | None = None,
    background: BackgroundTask | None = None,
) -> None:
    self.status_code = status_code
    if media_type is not None:
        self.media_type = media_type
    self.background = background
    self.body = self.render(content)
    self.init_headers(headers)

charset 類別屬性 實例屬性

charset = 'utf-8'

status_code 實例屬性

status_code = status_code

media_type 類別屬性 實例屬性

media_type = 'text/plain'

body 實例屬性

body = render(content)

background 實例屬性

background = background

headers 屬性

headers

render

render(content)
參數 說明
content(內容)

類型: Any(任何)

原始程式碼位於 starlette/responses.py
44
45
46
47
48
49
def render(self, content: typing.Any) -> bytes | memoryview:
    if content is None:
        return b""
    if isinstance(content, (bytes, memoryview)):
        return content
    return content.encode(self.charset)  # type: ignore

init_headers

init_headers(headers=None)
參數 說明
headers(標頭)

類型: Mapping[str, str] | None(字串對應或無) 預設值: None(無)

原始程式碼位於 starlette/responses.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def init_headers(self, headers: typing.Mapping[str, str] | None = None) -> None:
    if headers is None:
        raw_headers: list[tuple[bytes, bytes]] = []
        populate_content_length = True
        populate_content_type = True
    else:
        raw_headers = [(k.lower().encode("latin-1"), v.encode("latin-1")) for k, v in headers.items()]
        keys = [h[0] for h in raw_headers]
        populate_content_length = b"content-length" not in keys
        populate_content_type = b"content-type" not in keys

    body = getattr(self, "body", None)
    if (
        body is not None
        and populate_content_length
        and not (self.status_code < 200 or self.status_code in (204, 304))
    ):
        content_length = str(len(body))
        raw_headers.append((b"content-length", content_length.encode("latin-1")))

    content_type = self.media_type
    if content_type is not None and populate_content_type:
        if content_type.startswith("text/") and "charset=" not in content_type.lower():
            content_type += "; charset=" + self.charset
        raw_headers.append((b"content-type", content_type.encode("latin-1")))

    self.raw_headers = raw_headers
set_cookie(
    key,
    value="",
    max_age=None,
    expires=None,
    path="/",
    domain=None,
    secure=False,
    httponly=False,
    samesite="lax",
)
參數 說明
鍵值 (key)

類型: str

數值 (value)

類型: str 預設值: ''

最大存活時間 (max_age)

類型: int | None 預設值: None

到期時間 (expires)

類型: datetime | str | int | None 預設值: None

路徑 (path)

類型: str | None 預設值: '/'

網域 (domain)

類型: str | None(字串或無) 預設值: None(無)

安全連線 (secure)

類型: bool 預設值: False

僅限 HTTP (httponly)

類型: bool 預設值: False

SameSite 屬性 (samesite)

類型: Literal['lax', 'strict', 'none'] | None 預設值: 'lax'

原始程式碼位於 starlette/responses.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def set_cookie(
    self,
    key: str,
    value: str = "",
    max_age: int | None = None,
    expires: datetime | str | int | None = None,
    path: str | None = "/",
    domain: str | None = None,
    secure: bool = False,
    httponly: bool = False,
    samesite: typing.Literal["lax", "strict", "none"] | None = "lax",
) -> None:
    cookie: http.cookies.BaseCookie[str] = http.cookies.SimpleCookie()
    cookie[key] = value
    if max_age is not None:
        cookie[key]["max-age"] = max_age
    if expires is not None:
        if isinstance(expires, datetime):
            cookie[key]["expires"] = format_datetime(expires, usegmt=True)
        else:
            cookie[key]["expires"] = expires
    if path is not None:
        cookie[key]["path"] = path
    if domain is not None:
        cookie[key]["domain"] = domain
    if secure:
        cookie[key]["secure"] = True
    if httponly:
        cookie[key]["httponly"] = True
    if samesite is not None:
        assert samesite.lower() in [
            "strict",
            "lax",
            "none",
        ], "samesite must be either 'strict', 'lax' or 'none'"
        cookie[key]["samesite"] = samesite
    cookie_val = cookie.output(header="").strip()
    self.raw_headers.append((b"set-cookie", cookie_val.encode("latin-1")))
delete_cookie(
    key,
    path="/",
    domain=None,
    secure=False,
    httponly=False,
    samesite="lax",
)
參數 說明
鍵值 (key)

類型: str

路徑 (path)

類型: str 預設值: '/'

網域 (domain)

類型: str | None(字串或無) 預設值: None(無)

安全連線 (secure)

類型: bool 預設值: False

僅限 HTTP (httponly)

類型: bool 預設值: False

SameSite 屬性 (samesite)

類型: Literal['lax', 'strict', 'none'] | None 預設值: 'lax'

原始程式碼位於 starlette/responses.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def delete_cookie(
    self,
    key: str,
    path: str = "/",
    domain: str | None = None,
    secure: bool = False,
    httponly: bool = False,
    samesite: typing.Literal["lax", "strict", "none"] | None = "lax",
) -> None:
    self.set_cookie(
        key,
        max_age=0,
        expires=0,
        path=path,
        domain=domain,
        secure=secure,
        httponly=httponly,
        samesite=samesite,
    )

fastapi.responses.RedirectResponse

RedirectResponse(
    url, status_code=307, headers=None, background=None
)

基底類別: Response

參數 說明
url

類型: str | URL

status_code(狀態碼)

類型: int 預設值: 307

headers(標頭)

類型: Mapping[str, str] | None(字串對應或無) 預設值: None(無)

background(背景)

類型: BackgroundTask | None(背景任務或無) 預設值: None(無)

原始程式碼位於 starlette/responses.py
191
192
193
194
195
196
197
198
199
def __init__(
    self,
    url: str | URL,
    status_code: int = 307,
    headers: typing.Mapping[str, str] | None = None,
    background: BackgroundTask | None = None,
) -> None:
    super().__init__(content=b"", status_code=status_code, headers=headers, background=background)
    self.headers["location"] = quote(str(url), safe=":/%#?=@[]!$&'()*+,;")

charset 類別屬性 實例屬性

charset = 'utf-8'

status_code 實例屬性

status_code = status_code

media_type 類別屬性 實例屬性

media_type = None

body 實例屬性

body = render(content)

background 實例屬性

background = background

headers 屬性

headers

render

render(content)
參數 說明
content(內容)

類型: Any(任何)

原始程式碼位於 starlette/responses.py
44
45
46
47
48
49
def render(self, content: typing.Any) -> bytes | memoryview:
    if content is None:
        return b""
    if isinstance(content, (bytes, memoryview)):
        return content
    return content.encode(self.charset)  # type: ignore

init_headers

init_headers(headers=None)
參數 說明
headers(標頭)

類型: Mapping[str, str] | None(字串對應或無) 預設值: None(無)

原始程式碼位於 starlette/responses.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def init_headers(self, headers: typing.Mapping[str, str] | None = None) -> None:
    if headers is None:
        raw_headers: list[tuple[bytes, bytes]] = []
        populate_content_length = True
        populate_content_type = True
    else:
        raw_headers = [(k.lower().encode("latin-1"), v.encode("latin-1")) for k, v in headers.items()]
        keys = [h[0] for h in raw_headers]
        populate_content_length = b"content-length" not in keys
        populate_content_type = b"content-type" not in keys

    body = getattr(self, "body", None)
    if (
        body is not None
        and populate_content_length
        and not (self.status_code < 200 or self.status_code in (204, 304))
    ):
        content_length = str(len(body))
        raw_headers.append((b"content-length", content_length.encode("latin-1")))

    content_type = self.media_type
    if content_type is not None and populate_content_type:
        if content_type.startswith("text/") and "charset=" not in content_type.lower():
            content_type += "; charset=" + self.charset
        raw_headers.append((b"content-type", content_type.encode("latin-1")))

    self.raw_headers = raw_headers
set_cookie(
    key,
    value="",
    max_age=None,
    expires=None,
    path="/",
    domain=None,
    secure=False,
    httponly=False,
    samesite="lax",
)
參數 說明
鍵值 (key)

類型: str

數值 (value)

類型: str 預設值: ''

最大存活時間 (max_age)

類型: int | None 預設值: None

到期時間 (expires)

類型: datetime | str | int | None 預設值: None

路徑 (path)

類型: str | None 預設值: '/'

網域 (domain)

類型: str | None(字串或無) 預設值: None(無)

安全連線 (secure)

類型: bool 預設值: False

僅限 HTTP (httponly)

類型: bool 預設值: False

SameSite 屬性 (samesite)

類型: Literal['lax', 'strict', 'none'] | None 預設值: 'lax'

原始程式碼位於 starlette/responses.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def set_cookie(
    self,
    key: str,
    value: str = "",
    max_age: int | None = None,
    expires: datetime | str | int | None = None,
    path: str | None = "/",
    domain: str | None = None,
    secure: bool = False,
    httponly: bool = False,
    samesite: typing.Literal["lax", "strict", "none"] | None = "lax",
) -> None:
    cookie: http.cookies.BaseCookie[str] = http.cookies.SimpleCookie()
    cookie[key] = value
    if max_age is not None:
        cookie[key]["max-age"] = max_age
    if expires is not None:
        if isinstance(expires, datetime):
            cookie[key]["expires"] = format_datetime(expires, usegmt=True)
        else:
            cookie[key]["expires"] = expires
    if path is not None:
        cookie[key]["path"] = path
    if domain is not None:
        cookie[key]["domain"] = domain
    if secure:
        cookie[key]["secure"] = True
    if httponly:
        cookie[key]["httponly"] = True
    if samesite is not None:
        assert samesite.lower() in [
            "strict",
            "lax",
            "none",
        ], "samesite must be either 'strict', 'lax' or 'none'"
        cookie[key]["samesite"] = samesite
    cookie_val = cookie.output(header="").strip()
    self.raw_headers.append((b"set-cookie", cookie_val.encode("latin-1")))
delete_cookie(
    key,
    path="/",
    domain=None,
    secure=False,
    httponly=False,
    samesite="lax",
)
參數 說明
鍵值 (key)

類型: str

路徑 (path)

類型: str 預設值: '/'

網域 (domain)

類型: str | None(字串或無) 預設值: None(無)

安全連線 (secure)

類型: bool 預設值: False

僅限 HTTP (httponly)

類型: bool 預設值: False

SameSite 屬性 (samesite)

類型: Literal['lax', 'strict', 'none'] | None 預設值: 'lax'

原始程式碼位於 starlette/responses.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def delete_cookie(
    self,
    key: str,
    path: str = "/",
    domain: str | None = None,
    secure: bool = False,
    httponly: bool = False,
    samesite: typing.Literal["lax", "strict", "none"] | None = "lax",
) -> None:
    self.set_cookie(
        key,
        max_age=0,
        expires=0,
        path=path,
        domain=domain,
        secure=secure,
        httponly=httponly,
        samesite=samesite,
    )

fastapi.responses.Response

Response(
    content=None,
    status_code=200,
    headers=None,
    media_type=None,
    background=None,
)
參數 說明
content(內容)

類型: 任何 預設值:

status_code(狀態碼)

類型: int(整數) 預設值: 200

headers(標頭)

類型: Mapping[str, str] | None(字串對應或無) 預設值: None(無)

media_type(媒體類型)

類型: str | None(字串或無) 預設值: None(無)

background(背景)

類型: BackgroundTask | None(背景任務或無) 預設值: None(無)

原始程式碼位於 starlette/responses.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
def __init__(
    self,
    content: typing.Any = None,
    status_code: int = 200,
    headers: typing.Mapping[str, str] | None = None,
    media_type: str | None = None,
    background: BackgroundTask | None = None,
) -> None:
    self.status_code = status_code
    if media_type is not None:
        self.media_type = media_type
    self.background = background
    self.body = self.render(content)
    self.init_headers(headers)

charset 類別屬性 實例屬性

charset = 'utf-8'

status_code 實例屬性

status_code = status_code

media_type 類別屬性 實例屬性

media_type = None

body 實例屬性

body = render(content)

background 實例屬性

background = background

headers 屬性

headers

render

render(content)
參數 說明
content(內容)

類型: Any(任何)

原始程式碼位於 starlette/responses.py
44
45
46
47
48
49
def render(self, content: typing.Any) -> bytes | memoryview:
    if content is None:
        return b""
    if isinstance(content, (bytes, memoryview)):
        return content
    return content.encode(self.charset)  # type: ignore

init_headers

init_headers(headers=None)
參數 說明
headers(標頭)

類型: Mapping[str, str] | None(字串對應或無) 預設值: None(無)

原始程式碼位於 starlette/responses.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def init_headers(self, headers: typing.Mapping[str, str] | None = None) -> None:
    if headers is None:
        raw_headers: list[tuple[bytes, bytes]] = []
        populate_content_length = True
        populate_content_type = True
    else:
        raw_headers = [(k.lower().encode("latin-1"), v.encode("latin-1")) for k, v in headers.items()]
        keys = [h[0] for h in raw_headers]
        populate_content_length = b"content-length" not in keys
        populate_content_type = b"content-type" not in keys

    body = getattr(self, "body", None)
    if (
        body is not None
        and populate_content_length
        and not (self.status_code < 200 or self.status_code in (204, 304))
    ):
        content_length = str(len(body))
        raw_headers.append((b"content-length", content_length.encode("latin-1")))

    content_type = self.media_type
    if content_type is not None and populate_content_type:
        if content_type.startswith("text/") and "charset=" not in content_type.lower():
            content_type += "; charset=" + self.charset
        raw_headers.append((b"content-type", content_type.encode("latin-1")))

    self.raw_headers = raw_headers
set_cookie(
    key,
    value="",
    max_age=None,
    expires=None,
    path="/",
    domain=None,
    secure=False,
    httponly=False,
    samesite="lax",
)
參數 說明
鍵值 (key)

類型: str

數值 (value)

類型: str 預設值: ''

最大存活時間 (max_age)

類型: int | None 預設值: None

到期時間 (expires)

類型: datetime | str | int | None 預設值: None

路徑 (path)

類型: str | None 預設值: '/'

網域 (domain)

類型: str | None(字串或無) 預設值: None(無)

安全連線 (secure)

類型: bool 預設值: False

僅限 HTTP (httponly)

類型: bool 預設值: False

SameSite 屬性 (samesite)

類型: Literal['lax', 'strict', 'none'] | None 預設值: 'lax'

原始程式碼位於 starlette/responses.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def set_cookie(
    self,
    key: str,
    value: str = "",
    max_age: int | None = None,
    expires: datetime | str | int | None = None,
    path: str | None = "/",
    domain: str | None = None,
    secure: bool = False,
    httponly: bool = False,
    samesite: typing.Literal["lax", "strict", "none"] | None = "lax",
) -> None:
    cookie: http.cookies.BaseCookie[str] = http.cookies.SimpleCookie()
    cookie[key] = value
    if max_age is not None:
        cookie[key]["max-age"] = max_age
    if expires is not None:
        if isinstance(expires, datetime):
            cookie[key]["expires"] = format_datetime(expires, usegmt=True)
        else:
            cookie[key]["expires"] = expires
    if path is not None:
        cookie[key]["path"] = path
    if domain is not None:
        cookie[key]["domain"] = domain
    if secure:
        cookie[key]["secure"] = True
    if httponly:
        cookie[key]["httponly"] = True
    if samesite is not None:
        assert samesite.lower() in [
            "strict",
            "lax",
            "none",
        ], "samesite must be either 'strict', 'lax' or 'none'"
        cookie[key]["samesite"] = samesite
    cookie_val = cookie.output(header="").strip()
    self.raw_headers.append((b"set-cookie", cookie_val.encode("latin-1")))
delete_cookie(
    key,
    path="/",
    domain=None,
    secure=False,
    httponly=False,
    samesite="lax",
)
參數 說明
鍵值 (key)

類型: str

路徑 (path)

類型: str 預設值: '/'

網域 (domain)

類型: str | None(字串或無) 預設值: None(無)

安全連線 (secure)

類型: bool 預設值: False

僅限 HTTP (httponly)

類型: bool 預設值: False

SameSite 屬性 (samesite)

類型: Literal['lax', 'strict', 'none'] | None 預設值: 'lax'

原始程式碼位於 starlette/responses.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def delete_cookie(
    self,
    key: str,
    path: str = "/",
    domain: str | None = None,
    secure: bool = False,
    httponly: bool = False,
    samesite: typing.Literal["lax", "strict", "none"] | None = "lax",
) -> None:
    self.set_cookie(
        key,
        max_age=0,
        expires=0,
        path=path,
        domain=domain,
        secure=secure,
        httponly=httponly,
        samesite=samesite,
    )

fastapi.responses.StreamingResponse

StreamingResponse(
    content,
    status_code=200,
    headers=None,
    media_type=None,
    background=None,
)

基底類別: Response

參數 說明
content(內容)

類型: ContentStream

status_code(狀態碼)

類型: int(整數) 預設值: 200

headers(標頭)

類型: Mapping[str, str] | None(字串對應或無) 預設值: None(無)

media_type(媒體類型)

類型: str | None(字串或無) 預設值: None(無)

background(背景)

類型: BackgroundTask | None(背景任務或無) 預設值: None(無)

原始程式碼位於 starlette/responses.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
def __init__(
    self,
    content: ContentStream,
    status_code: int = 200,
    headers: typing.Mapping[str, str] | None = None,
    media_type: str | None = None,
    background: BackgroundTask | None = None,
) -> None:
    if isinstance(content, typing.AsyncIterable):
        self.body_iterator = content
    else:
        self.body_iterator = iterate_in_threadpool(content)
    self.status_code = status_code
    self.media_type = self.media_type if media_type is None else media_type
    self.background = background
    self.init_headers(headers)

body_iterator 實例屬性

body_iterator

charset 類別屬性 實例屬性

charset = 'utf-8'

status_code 實例屬性

status_code = status_code

media_type 實例屬性

media_type = (
    media_type if media_type is None else media_type
)

body 實例屬性

body = render(content)

background 實例屬性

background = background

headers 屬性

headers

render

render(content)
參數 說明
content(內容)

類型: Any(任何)

原始程式碼位於 starlette/responses.py
44
45
46
47
48
49
def render(self, content: typing.Any) -> bytes | memoryview:
    if content is None:
        return b""
    if isinstance(content, (bytes, memoryview)):
        return content
    return content.encode(self.charset)  # type: ignore

init_headers

init_headers(headers=None)
參數 說明
headers(標頭)

類型: Mapping[str, str] | None(字串對應或無) 預設值: None(無)

原始程式碼位於 starlette/responses.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def init_headers(self, headers: typing.Mapping[str, str] | None = None) -> None:
    if headers is None:
        raw_headers: list[tuple[bytes, bytes]] = []
        populate_content_length = True
        populate_content_type = True
    else:
        raw_headers = [(k.lower().encode("latin-1"), v.encode("latin-1")) for k, v in headers.items()]
        keys = [h[0] for h in raw_headers]
        populate_content_length = b"content-length" not in keys
        populate_content_type = b"content-type" not in keys

    body = getattr(self, "body", None)
    if (
        body is not None
        and populate_content_length
        and not (self.status_code < 200 or self.status_code in (204, 304))
    ):
        content_length = str(len(body))
        raw_headers.append((b"content-length", content_length.encode("latin-1")))

    content_type = self.media_type
    if content_type is not None and populate_content_type:
        if content_type.startswith("text/") and "charset=" not in content_type.lower():
            content_type += "; charset=" + self.charset
        raw_headers.append((b"content-type", content_type.encode("latin-1")))

    self.raw_headers = raw_headers
set_cookie(
    key,
    value="",
    max_age=None,
    expires=None,
    path="/",
    domain=None,
    secure=False,
    httponly=False,
    samesite="lax",
)
參數 說明
鍵值 (key)

類型: str

數值 (value)

類型: str 預設值: ''

最大存活時間 (max_age)

類型: int | None 預設值: None

到期時間 (expires)

類型: datetime | str | int | None 預設值: None

路徑 (path)

類型: str | None 預設值: '/'

網域 (domain)

類型: str | None(字串或無) 預設值: None(無)

安全連線 (secure)

類型: bool 預設值: False

僅限 HTTP (httponly)

類型: bool 預設值: False

SameSite 屬性 (samesite)

類型: Literal['lax', 'strict', 'none'] | None 預設值: 'lax'

原始程式碼位於 starlette/responses.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def set_cookie(
    self,
    key: str,
    value: str = "",
    max_age: int | None = None,
    expires: datetime | str | int | None = None,
    path: str | None = "/",
    domain: str | None = None,
    secure: bool = False,
    httponly: bool = False,
    samesite: typing.Literal["lax", "strict", "none"] | None = "lax",
) -> None:
    cookie: http.cookies.BaseCookie[str] = http.cookies.SimpleCookie()
    cookie[key] = value
    if max_age is not None:
        cookie[key]["max-age"] = max_age
    if expires is not None:
        if isinstance(expires, datetime):
            cookie[key]["expires"] = format_datetime(expires, usegmt=True)
        else:
            cookie[key]["expires"] = expires
    if path is not None:
        cookie[key]["path"] = path
    if domain is not None:
        cookie[key]["domain"] = domain
    if secure:
        cookie[key]["secure"] = True
    if httponly:
        cookie[key]["httponly"] = True
    if samesite is not None:
        assert samesite.lower() in [
            "strict",
            "lax",
            "none",
        ], "samesite must be either 'strict', 'lax' or 'none'"
        cookie[key]["samesite"] = samesite
    cookie_val = cookie.output(header="").strip()
    self.raw_headers.append((b"set-cookie", cookie_val.encode("latin-1")))
delete_cookie(
    key,
    path="/",
    domain=None,
    secure=False,
    httponly=False,
    samesite="lax",
)
參數 說明
鍵值 (key)

類型: str

路徑 (path)

類型: str 預設值: '/'

網域 (domain)

類型: str | None(字串或無) 預設值: None(無)

安全連線 (secure)

類型: bool 預設值: False

僅限 HTTP (httponly)

類型: bool 預設值: False

SameSite 屬性 (samesite)

類型: Literal['lax', 'strict', 'none'] | None 預設值: 'lax'

原始程式碼位於 starlette/responses.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def delete_cookie(
    self,
    key: str,
    path: str = "/",
    domain: str | None = None,
    secure: bool = False,
    httponly: bool = False,
    samesite: typing.Literal["lax", "strict", "none"] | None = "lax",
) -> None:
    self.set_cookie(
        key,
        max_age=0,
        expires=0,
        path=path,
        domain=domain,
        secure=secure,
        httponly=httponly,
        samesite=samesite,
    )