์๋ต ํค๋¶
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
๋ฅผ ์ง์ ์ ์ผ๋ก ๋ฐํํ ๋ ํค๋๋ฅผ ์ถ๊ฐํ ์๋ ์์ต๋๋ค.
์๋ต ์ง์ ๋ฐํํ๊ธฐ์ ์ค๋ช ๋ ๊ฒ ์ฒ๋ผ ์๋ต์ ๋ง๋ค์ด ์ถ๊ฐ์ ์ธ ๋งค๊ฐ ๋ณ์์ ํจ๊ป ํค๋๋ฅผ ๋๊ธฐ๋ฉด ๋ฉ๋๋ค.
Create a response as described in Return a Response Directly and pass the headers as an additional parameter:
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
๋ก ์ด๋ฆ์ ๋ฐ๊ฟ ์ ๊ณตํ๊ณ ์์ต๋๋ค. ๋๋ถ๋ถ์ ๊ฐ๋ฅํ ์๋ต์ Starlette์์ ์ง์ ์ ๊ณตํ๊ณ ์์ต๋๋ค.
๊ทธ๋ฆฌ๊ณ Response
๋ ํค๋์ ์ฟ ํค๋ฅผ ์ค์ ํ๋ ๋ฐ ์์ฃผ ์ฌ์ฉํ ์ ์์ผ๋ฏ๋ก, FastAPI๋ํ ์ด๊ฑธ fastapi.Response
๋ก ์ ๊ณตํ๊ณ ์์ต๋๋ค.
์ปค์คํ ํค๋¶
'X-' ์ ๋์ฌ๋ฅผ ์ด์ฉํด ์ฌ์ฉ์ ์ ์ ๋ ์ ํค๋๋ฅผ ์ถ๊ฐํ ์๋ ์์์ ์ผ๋์ ๋์ญ์์ค.
ํ์ง๋ง ๋ธ๋ผ์ฐ์ ์์ ํด๋ผ์ด์ธํธ๊ฐ ๋ณผ ์ ์๋ ์ปค์คํ
ํค๋๋ฅผ ๊ฐ๊ฒ ํ ๋ ค๋ฉด CORS ์ค์ ์์ ์ด๋ฅผ ์ถ๊ฐํด์ผ ๋ฉ๋๋ค. (CORS (Cross-Origin Resource Sharing)์์ ์์ธํ ์ฝ์ด๋ณด์ธ์.) Starlette's CORS docs์์ ์ค๋ช
๋ expose_headers
๋ฅผ ์ฌ์ฉํ์ธ์.