'ascii'编解码器无法解码位置0中的字节0xb7:序数不在范围内(128)

时间:2016-06-20 09:57:31

标签: django python-2.7 utf-8 big5

我正在尝试在我的django项目中发送短信,这是我的短信功能

  

mit2sms.py

import urllib
import urllib2



def sendsms(phonenumber,textcontent):
    textcontent=textcontent.decode('utf8').encode('big5') #10
    #textcontent=textcontent.encode('big5')  #9
    url = "https://urls?username=myname&password=mypassword&dstaddr="+phonenumber+"&smbody="+textcontent
    req = urllib2.Request(url)
    response = urllib2.urlopen(req)

我可以在python shell中用中文和英文发送短信确定。但是当我将它导入我的django项目时我就得到了

'ascii' codec can't decode byte 0xb7 in position 0: ordinal not in range(128)

错误

我的django

  

views.py

#-*- coding: utf-8 -*-
....
from mit2sms import *   # I import the sms function here
....

def register(request):
    ....
    tel = request.POST['tel']
    textcontent = "會員申請通過"
    sendsms(tel,textcontent)
    ....

views.py和mit2sms.py位于同一目录

但在我注册后我收到了错误

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/register/

Django Version: 1.9.7
Python Version: 2.7.11
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'member']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "/Users/korekyourin/books/stayreal/sandbox/member_register/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  149.                     response = self.process_exception_by_middleware(e, request)

File "/Users/korekyourin/books/stayreal/sandbox/member_register/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/korekyourin/books/stayreal/sandbox/member_register/member_register/member/views.py" in register
  57.     sendsms(tel,textcontent)

File "/Users/korekyourin/books/stayreal/sandbox/member_register/member_register/member/mit2sms.py" in sendsms
  10.     url = "https://urls?username=myname&password=mypassword&dstaddr="+phonenumber+"&smbody="+textcontent

Exception Type: UnicodeDecodeError at /register/
Exception Value: 'ascii' codec can't decode byte 0xb7 in position 0: ordinal not in range(128)

2 个答案:

答案 0 :(得分:1)

尝试修复此行:

SecureRandom

为:

textcontent = "會員申請通過"` 

答案 1 :(得分:1)

当您将str隐式转换为Unicode时,您倾向于获得UnicodeDecodeError UnicodeDecodeError: 'ascii' codec can't decode

这可能在以下情况下发生:

unicode('€')                       # explicit conversion without encoding
u"The currency is: {}".format('€') # new style format string into Unicode string - Python will try to convert value string to Unicode first
u'The currency is: %s' % '€'       # old style format string into Unicode string - Python will try to convert value string to Unicode first
u'The currency is: ' + '€'         # append string to Unicode - Python will try to convert string to Unicode first

后者可能就是你所要达到的 - 将str附加到Unicode上。 Python将首先尝试将str转换为Unicode,但只会使用" ascii"编解码器(Python 2.x),对于非ascii内容将失败。

它并不是很明显,但您很可能从以下位置获取Unicode对象:

tel = request.POST['tel']

然后,当您将tel / phonenumber(一个Unicode对象)添加到textcontent(您的big5编码的str)时,您将获得UnicodeDecodeError

答案是删除任何隐含的转换并删除不必要的解码/编码。

变化:

textcontent = u"會員申請通過" # Note the 'u`. textcontent is now a Unicode

并将sendsms()更改为:

def sendsms(phonenumber,textcontent):
    url = u"https://urls?username=myname&password=mypassword&dstaddr="+phonenumber+"&smbody="+textcontent
    # now a unicode also
    # better written using String.format(): 
    # url = u"https://urls?username=myname&password=mypassword&dstaddr={phonenumber}&smbody={textcontent}".format(phonenumber=phonenumber, textcontent=textcontent)
    req = urllib2.Request(url.encode('big5')) # encode only when absolutely necessary
    response = urllib2.urlopen(req)