次のようなエラー メッセージが表示されます。
Internal Server Error: /Translator/
Traceback (most recent call last):
File "D:\Python27\lib\site-packages\django\core\handlers\base.py", line 115, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "D:\Project\Reservation\Translator\views.py", line 72, in getParams
content = request.POST['content'].decode('utf-8').encode('utf-8')
File "D:\Python27\lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
[05/Oct/2013 23:32:51] "POST /Translator/ HTTP/1.1" 500 65244
Internal Server Error: /Translator/
Traceback (most recent call last):
File "D:\Python27\lib\site-packages\django\core\handlers\base.py", line 115, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "D:\Project\Reservation\Translator\views.py", line 72, in getParams
content = request.POST['content'].decode('utf-8').encode('utf-8')
File "D:\Python27\lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 2: ordinal not in range(128)
私のコードは次のとおりです。
def get_access_token():
post_data = urllib.urlencode({'client_id':client_id,'client_secret':client_secret, 'scope':ACCESS_TOKEN_SCOPE, 'grant_type':ACCESS_TOKEN_GRANT_TYPE })
token_data = json.loads(requests.post(ACCESS_TOKEN_URL,data=post_data).content)
access_token = token_data["access_token"]
return access_token
def detect(access_token,detect_text):
headers = {'Authorization': 'bearer'+ ' ' + access_token}
detect_url_all = DETECT_URL + "?" + urllib.urlencode({'text':detect_text})
detect_language = requests.get(detect_url_all,headers=headers).content[3:]
return detect_language
def Translator(text,orignal,access_token):
headers = {'Authorization': 'bearer'+ ' ' + access_token}
translation_ars = {
'text': text,
'to': 'zh',
'from': orignal
}
transate_url_all = TRANSLATE_URL + "?" + urllib.urlencode(translation_ars)
result = requests.get(transate_url_all,headers=headers).content
return result
def getParams(request):
if request.method == 'POST':
form = Junk(request.POST)
if form.is_valid():
content = request.POST['content'].decode('utf-8').encode('utf-8')
country = detect(get_access_token(),content)
result = Translator(content,country,get_access_token())
return render_to_response('Translator/translate.html',{'result':result})
else:
form = Junk()
return render_to_response('Translator/index.html',{'form': form})
まず、テキストの言語を最初に検出したいと思います。私のプログラムは、テキストのコーディングが何であるかを知ることができないため、デコードまたはエンコードを行うことができません。