0

我正在尝试在我的 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

视图.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)
4

2 回答 2

1

尝试修复这一行:

textcontent = "會員申請通過"` 

到:

textcontent = u"會員申請通過".encode('utf-8')
于 2016-06-20T14:22:20.893 回答
1

UnicodeDecodeError UnicodeDecodeError: 'ascii' codec can't decode当您将 str 隐式转换为 Unicode 时,您往往会得到。

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

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)
于 2016-06-20T15:03:01.233 回答