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