python header filename 추출
외부 url에서 파일 다운로드 한 후, 바로 업로드하는 것이 목표
- python requests 라이브러리 사용
- 문제는 한글 파일 이름 처리하는 것
해결방법
- header에서 filename을 추출
- urldecode(unqoute) 해줘야함
- chardet 라이브러리를 사용해서 filename의 인코딩을 파악
- 파악한 인코딩을 디코드 -> 인코드(utf8) 순서로 진행
- 한글 이름을 urlencode(quote)
- 업로드
순서는 다운로드 -> 헤더 content-disopsion 추출 -> urldecode -> 문자열 디코딩 및 utf-8 인코딩 -> urlencode
r_download = requests.get(download_url)
header = unqoute(r_download.headers['Content-Disposition'])
decode = header.decode(chardet.detect(header)['encoding'])
encode = decode.encode('utf8')
file_name = re.findall("filename=(.+)", encode)[0]
payload = {'file': (quote(file_name), body)}
r_upload = requests.post(upload_url, files=payload, headers=headers)
문제점
- 그러나 chardet에서 정확하게 홈페이지의 인코딩을 파악못할 경우가 발생
- 이 경우 한글 깨짐
- 결국 크롤링 시 한글 이름 모두 저장 후, 파일 업로드 시 urlencode만 사용
Written on 2016 Dec, 23