2022-02-25 WIL

Grolar Kim·2022년 2월 25일
1

TIL-WIL

목록 보기
5/17

장고 프로젝트를 진행하던 중 form을 통해서 파일이나 이미지를 주고 받을 때 오류가 생겼었다. 해결책을 찾아보던 중 스택오버플로우에 좋은 글이 있어서 가져왔다.

원문 : https://stackoverflow.com/questions/10434599/get-the-data-received-in-a-flask-request

The docs describe the attributes available on the request object (from flask import request) during a request. In most common cases request.data will be empty because it's used as a fallback:
request.data Contains the incoming request data as string in case it came with a mimetype Flask does not handle.

  • request.args: the key/value pairs in the URL query string
  • request.form: the key/value pairs in the body, from a HTML post form, or JavaScript request that isn't JSON encoded
  • request.files: the files in the body, which Flask keeps separate from form. HTML forms must use enctype=multipart/form-data or files will not be uploaded.
  • request.values: combined args and form, preferring args if keys overlap
  • request.json: parsed JSON data. The request must have the application/json content type, or use request.get_json(force=True) to ignore the content type.

All of these are MultiDict instances (except for json). You can access values using:

  • request.form['name']: use indexing if you know the key exists
  • request.form.get('name'): use get if the key might not exist
  • request.form.getlist('name'): use getlist if the key is sent multiple times and you want a list of values. get only returns the first value.

글에서는 django뿐만 아니라 flask에서도 사용할 수 있는 request에 관한 사용법이 정리되어있었다.
특히 내가 문제가 생겼던 request.files에서 html에 enctype=multipart/form-data를 사용해야 파일이 정상적으로 업로드 된다는 것도 정리 되어있었다.
장고 템플릿을 사용하여서 form을 통해 파일을 주고 받을 때 multipart/form-data를 붙여서 사용해서 해결할 수 있었다.

1개의 댓글

comment-user-thumbnail
2022년 3월 2일

프로젝트 하면서 좀 더 성장하는 계기가 되길

답글 달기