[FastAPI] reponse["content-disposition"] === undefined ???

항상 정리하기·2022년 1월 29일
0

fastapi

목록 보기
1/1

fastapi에서 파일이나 stream을 응답할 때 FileResponse를 구성해서 응답한다.
파일명을 포함하는 방법은 아래와 같이 filename 인자를 추가해주면 응답 헤더 content-disposition에 filename이 추가된다.

## https://fastapi.tiangolo.com/ko/advanced/custom-response/?h=#fileresponse

import uvicorn as uvicorn
from fastapi import FastAPI
from fastapi.responses import FileResponse

some_file_path = "pyproject.toml"
app = FastAPI()


@app.get("/")
async def main():
    return FileResponse(some_file_path, filename=some_file_path)


if __name__ == "__main__":
    uvicorn.run("main:app", reload=True)

브라우저 개발자 화면에서 보이는 Reponse Headers에 포함된 content-disposition

하지만 javascript에서 읽으려고 하니 undefined가 나온다.

뭐가 문젤까..

검색을 해보니 백엔드의 cors 설정 문제이고 expose header 설정이 필요하다고 하여 fastapi 공식 가이드에 나온데로 아래와 같이 설정해봤지만 결과는 동일했다.

## https://fastapi.tiangolo.com/tutorial/cors/

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

origins = [
    "http://localhost.tiangolo.com",
    "https://localhost.tiangolo.com",
    "http://localhost",
    "http://localhost:8080",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/")
async def main():
    return {"message": "Hello World"}

고민하던 차에 CORSMiddleware 객체 정의부 소스를 살펴보니

class CORSMiddleware:
    def __init__(
        self,
        app: ASGIApp,
        allow_origins: typing.Sequence[str] = (),
        allow_methods: typing.Sequence[str] = ("GET",),
        allow_headers: typing.Sequence[str] = (),
        allow_credentials: bool = False,
        allow_origin_regex: str = None,
        expose_headers: typing.Sequence[str] = (),
        max_age: int = 600,
    ) -> None:

여기에 expose_headers 옵션이 있었구나!

그래서 아래와 같이 옵션을 추가하니 해결~~

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
    expose_headers=["*"],
)

오늘의 교훈..

프레임워크의 기능을 구글링해서 못 찾겠으면 정의된 코드를 찾아보자!

다 적고 보니 아래 링크에 잘 설명되어 있다..
https://fastapi.tiangolo.com/ko/tutorial/cors/?h=

다시 적어보는 오늘의 교훈

우선 tutorial을 잘 읽어볼것!!

profile
늦은 것 같지만 이제부터라도 차근차근 하나씩 정리하기

0개의 댓글