最近在学习python的web开发,用了下django,按照django基础教程使用django的命令创建web工程:
环境:
win7
python2.7.10
django1.8.6
1、创建一个项目
django-admin startproject mysite
2、创建一个应用
python manage.py startapp learn
把我们新定义的app加到settings.py中的INSTALL_APPS中
修改mysite/mysite/settings.py
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'learn',
)
3、定义learn的视图,修改mysite/learn/views.py
#coding:utf-8
from django.http import HttpResponse
def index(request):
return HttpResponse(u"欢迎光临 自强学堂!")
4、定义视图函数的url:修改mysite/mysite/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'learn.views.index', name='home'),# Notice this line
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
5、运行服务器
python manage.py runserver
6、打开浏览器,访问 http://127.0.0.1:8000/
7、浏览报错:
(unicode error) 'utf8' codec can't decode byte 0xbb in position 0: invalid start byte (views.py, line 8)
8、原因分析:
从网上搜索了下,即使使用以下方式还是错误
HttpResponse(unicode("欢迎光临 自强学堂!"))
HttpResponse(unicode("欢迎光临 自强学堂!").encode("utf-8"))
HttpResponse(u"欢迎光临 自强学堂!")
HttpResponse(u"欢迎光临 自强学堂!".encode("utf-8"))
django生成的views.py文件使用ansi编码保存,而我使用了中文,最好使用utf-8编码保存
使用notepad++使用utf-8编码保存后,问题解决!!
HttpResponse(u"欢迎光临 自强学堂!")---正确!!
HttpResponse(u"欢迎光临 自强学堂!".encode("utf-8"))---正确!!
HttpResponse(unicode("欢迎光临 自强学堂!"))----错误!!
HttpResponse(unicode("欢迎光临 自强学堂!").encode("utf-8"))----错误!!
9、总结
涉及到中文等非ansi字符的开发,py文件最好均用utf-8编码保存