본문 바로가기
Development/Python

파이썬 requests 의 multipart/form-data 활용

by 폴피드 2024. 6. 27.
728x90
반응형

FastAPI 로 아래와 같이 코드를 작성 했다.

@router.post(
    "/v1/file",
    name="Upload File",
)
def upload_file(
  name: Annotated[str, Form()],
  language: Annotated[str, Form()],
  file: Annotated[UploadFile, Form()]
):

그리고 이 API 를 호출 하기위해 Test 코드를 작성했는데 아래와 같이 작성을 했다.

def test_file_upload(self):
    file: UploadFile = open("./테스트.txt", "rb")

    # curl 명령에 필요한 헤더 설정
    headers = {
        "token": "XXXXXXXX",
        "Content-type": "multipart/form-data;"
    }

    # curl 명령에 필요한 폼 데이터 설정
    form_data = {"name": "test", "language": "korean"}

    # curl 명령 실행
    response = requests.post(
        f"{ENDPOINT_URL}/v1/file",
        headers=headers,
        data=form_data,
        files={"file": file},
    )

    # 응답 반환
    print(response.json())

여기에서부터 삽질이 시작됐다. 당연히 저렇게 하면 될줄 알았다....

우선 위에 테스트의 결과는 이렇게 나왔다.
{'detail': 'Missing boundary in multipart.'}

그래서 boundary 를 넣어야 하나 해서 넣어봤다. 하지만 결과는 또 에러가 나왔다. 
{'detail': 'There was an error parsing the body'}

분명 잘 한것 같은데 왜 그러지 하다가 header 에 content-type 을 삭제해봤다. 그랬더니 정상동작 -_-;;; 무슨 차이가 있을까 궁금해서 header 를 디버깅 해봤다.

{'User-Agent': 'python-requests/2.27.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-type': 'multipart/form-data', 'Content-Length': '6413'}
{'User-Agent': 'python-requests/2.27.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '6413', 'Content-Type': 'multipart/form-data; boundary=0689cf142145921f2ee5a550db249b51'}
{'User-Agent': 'python-requests/2.27.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Type': 'multipart/form-data; boundary=0689cf142145921f2ee5a550db249b51', 'Content-Length': '6413'}

첫번째 : multipart/form-data 를 넣은경우  -------> 응답 에러
두번째 : 안넣은 경우 -------> 정상
세번째 : 안넣은 경우의 값을 강제로 넣은 경우 -------> 응답 에러

두번째와 세번째의 차이는 Content-Length 의 순서 밖에 없는데 왜 이런 결과가 나오는지 모르겠다. ㅡ,ㅡ;;

 

728x90
반응형