요청 라 이브 러 리 에서 파일 을 업로드 할 때 UnicodeDecodeError:'ascii'codec 에서 바이트 오 류 를 디 코딩 할 수 없습니다.
10589 단어 unicode
2013-12-20 20:51:09,235 __main__ ERROR 'ascii' codec can't decode byte 0xe7 in position 27379: ordinal not in range(128)
Traceback (most recent call last):
File "server_merge.py", line 251, in avml_storage
result_f , result_m = avml_storage.uploadData( storage_key, xml_content )
File "/opt/ResultCollector/app/utils/ADFSAvml.py", line 33, in uploadData
r = requests.post(uploadUrl, files=f)
File "/usr/local/lib/python2.7/site-packages/requests-1.2.3-py2.7.egg/requests/api.py", line 88, in post
return request('post', url, data=data, **kwargs)
File "/usr/local/lib/python2.7/site-packages/requests-1.2.3-py2.7.egg/requests/api.py", line 44, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/local/lib/python2.7/site-packages/requests-1.2.3-py2.7.egg/requests/sessions.py", line 335, in request
resp = self.send(prep, **send_kwargs)
File "/usr/local/lib/python2.7/site-packages/requests-1.2.3-py2.7.egg/requests/sessions.py", line 438, in send
r = adapter.send(request, **kwargs)
File "/usr/local/lib/python2.7/site-packages/requests-1.2.3-py2.7.egg/requests/adapters.py", line 292, in send
timeout=timeout
File "/usr/local/lib/python2.7/site-packages/requests-1.2.3-py2.7.egg/requests/packages/urllib3/connectionpool.py", line 428, in urlopen
body=body, headers=headers)
File "/usr/local/lib/python2.7/site-packages/requests-1.2.3-py2.7.egg/requests/packages/urllib3/connectionpool.py", line 280, in _make_request
conn.request(method, url, **httplib_request_kw)
File "/usr/local/lib/python2.7/httplib.py", line 946, in request
self._send_request(method, url, body, headers)
File "/usr/local/lib/python2.7/httplib.py", line 987, in _send_request
self.endheaders(body)
File "/usr/local/lib/python2.7/httplib.py", line 940, in endheaders
self._send_output(message_body)
File "/usr/local/lib/python2.7/httplib.py", line 801, in _send_output
msg += message_body
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 27379: ordinal not in range(128)
traceback 에서 쉽게 알 아 볼 수 있 습 니 다.잘못된 위 치 는 httplib.py 에 있 는 일 것 입 니 다.send_output 함수 에 서 는 유 니 코드 와 str 를 혼용 한 것 일 수 있 습 니 다.추적 을 통 해 msg 는 유 니 코드 형식,message 임 을 알 수 있 습 니 다.body 는 str 타 입 입 입 니 다.계속 앞으로 거 슬러 올 라 가면 Requests 가 Content-Length 를 유 니 코드 로 설정 한 것 을 알 수 있 습 니 다.조작 하기 편 하도록 Request 는 copat.py 에서 str 를 전의 한 것 같 습 니 다.
if is_py2:
from urllib import quote, unquote, quote_plus, unquote_plus, urlencode
from urlparse import urlparse, urlunparse, urljoin, urlsplit, urldefrag
from urllib2 import parse_http_list
import cookielib
from Cookie import Morsel
from StringIO import StringIO
from .packages.urllib3.packages.ordered_dict import OrderedDict
builtin_str = str
bytes = str
str = unicode
basestring = basestring
numeric_types = (int, long, float)
그래서 Requests 에서 사용 하 는 str 는 모두 유 니 코드 형식의 데이터 입 니 다.output、_send_output 와 puutheader 몇 가지 함수 에서 문제 가 puutheader 함수 에서 header 를 처리 하 는 데 발생 할 수 있 음 을 알 수 있 습 니 다.유 니 코드 를 str 로 변환 하지 않 아서 발생 할 수 있 습 니 다.putheader 코드 는 다음 과 같 습 니 다:
def putheader(self, header, value):
"""Send a request header line to the server.
For example: h.putheader('Accept', 'text/html')
"""
if self.__state != _CS_REQ_STARTED:
raise CannotSendHeader()
str = '%s: %s' % (header, value)
self._output(str)
우연 한 기회 에 똑 같은 조작 방식 을 발 견 했 습 니 다.Request 로 파일 을 업로드 하면 다른 기계 에서 사용 하기 좋 습 니 다.두 기계 의 환경 을 비교 해 보면 Python 버 전 만 일치 하지 않 습 니 다.하 나 는 Python 2.7 이 고 하 나 는 Python 2.7.3 입 니 다.httplib.py 에 비해 기능 이 정상 적 으로 작 동 하 는 기계(Python 2.7.3)에서 puutheader 의 코드 는 다음 과 같 습 니 다.
def putheader(self, header, *values):
"""Send a request header line to the server.
For example: h.putheader('Accept', 'text/html')
"""
if self.__state != _CS_REQ_STARTED:
raise CannotSendHeader()
hdr = '%s: %s' % (header, '\r
\t'.join([str(v) for v in values]))
self._output(hdr)
비 교 를 통 해 알 수 있 듯 이 Python 2.7.3 은 들 어 오 는 value 에 대해 명시 적 전환 을 했 고 잠재 적 인 오 류 를 피 한 적 이 없다.또 몇 가지 버 전 을 검증 한 결과 파 이 썬 2.6.6,파 이 썬 2.7 은 Requests 라 이브 러 리 를 사용 할 때 문제 가 있 었 고 파 이 썬 2.7.3,파 이 썬 2.7.5 는 문제 가 없 었 다.Python 버 전 을 2.7.3 이상으로 업그레이드 하 는 것 을 권장 합 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JS의 문자열에서 베트남어 문자 제거텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.